SConstruct revision 3940
12SN/A# -*- mode:python -*-
21762SN/A
32SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
42SN/A# All rights reserved.
52SN/A#
62SN/A# Redistribution and use in source and binary forms, with or without
72SN/A# modification, are permitted provided that the following conditions are
82SN/A# met: redistributions of source code must retain the above copyright
92SN/A# notice, this list of conditions and the following disclaimer;
102SN/A# redistributions in binary form must reproduce the above copyright
112SN/A# notice, this list of conditions and the following disclaimer in the
122SN/A# documentation and/or other materials provided with the distribution;
132SN/A# neither the name of the copyright holders nor the names of its
142SN/A# contributors may be used to endorse or promote products derived from
152SN/A# this software without specific prior written permission.
162SN/A#
172SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
182SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
192SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
202SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
212SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
222SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
232SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
242SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
252SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
262SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
272665Ssaidi@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
292665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
302SN/A
312SN/A###################################################
325569Snate@binkert.org#
335569Snate@binkert.org# SCons top-level build description (SConstruct) file.
342SN/A#
355569Snate@binkert.org# While in this directory ('m5'), just type 'scons' to build the default
367678Sgblack@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
373614Sgblack@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
383614Sgblack@eecs.umich.edu# the optimized full-system version).
392166SN/A#
402147SN/A# You can build M5 in a different directory as long as there is a
415569Snate@binkert.org# 'build/<CONFIG>' somewhere along the target path.  The build system
422167SN/A# expects that all configs under the same build directory are being
4311294Sandreas.hansson@arm.com# built for the same host system.
442090SN/A#
452222SN/A# Examples:
462090SN/A#
472201SN/A#   The following two commands are equivalent.  The '-u' option tells
482201SN/A#   scons to search up the directory tree for this SConstruct file.
492201SN/A#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
502112SN/A#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
5110474Sandreas.hansson@arm.com#
5210417Sandreas.hansson@arm.com#   The following two commands are equivalent and demonstrate building
5310417Sandreas.hansson@arm.com#   in a directory outside of the source tree.  The '-C' option tells
542175SN/A#   scons to chdir to the specified directory to find this SConstruct
552222SN/A#   file.
562SN/A#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
572SN/A#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
582203SN/A#
592166SN/A# You can use 'scons -H' to print scons options.  If you're in this
602166SN/A# 'm5' directory (or use -u or -C to tell scons where to find this
612203SN/A# file), you can use 'scons -h' to print all the M5-specific build
622166SN/A# options as well.
632222SN/A#
645569Snate@binkert.org###################################################
652166SN/A
664695Sgblack@eecs.umich.edu# Python library imports
672166SN/Aimport sys
682222SN/Aimport os
692166SN/Aimport subprocess
702166SN/Afrom os.path import join as joinpath
712203SN/A
722166SN/A# Check for recent-enough Python and SCons versions.  If your system's
732166SN/A# default installation of Python is not recent enough, you can use a
742203SN/A# non-default installation of the Python interpreter by either (1)
752166SN/A# rearranging your PATH so that scons finds the non-default 'python'
762222SN/A# first or (2) explicitly invoking an alternative interpreter on the
775569Snate@binkert.org# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
782166SN/AEnsurePythonVersion(2,4)
794695Sgblack@eecs.umich.edu
802166SN/A# Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
812222SN/A# 3-element version number.
824695Sgblack@eecs.umich.edumin_scons_version = (0,96,91)
832166SN/Atry:
842166SN/A    EnsureSConsVersion(*min_scons_version)
852147SN/Aexcept:
862090SN/A    print "Error checking current SCons version."
872147SN/A    print "SCons", ".".join(map(str,min_scons_version)), "or greater required."
882147SN/A    Exit(2)
892147SN/A    
902222SN/A
915569Snate@binkert.org# The absolute path to the current directory (where this file lives).
922112SN/AROOT = Dir('.').abspath
934695Sgblack@eecs.umich.edu
942147SN/A# Path to the M5 source tree.
952222SN/ASRCDIR = joinpath(ROOT, 'src')
962147SN/A
972090SN/A# tell python where to find m5 python code
982147SN/Asys.path.append(joinpath(ROOT, 'src/python'))
992090SN/A
1002147SN/A###################################################
1012147SN/A#
1022147SN/A# Figure out which configurations to set up based on the path(s) of
1032222SN/A# the target(s).
1045569Snate@binkert.org#
1055569Snate@binkert.org###################################################
1065569Snate@binkert.org
1075569Snate@binkert.org# Find default configuration & binary.
1082112SN/ADefault(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
1094695Sgblack@eecs.umich.edu
1102147SN/A# helper function: find last occurrence of element in list
1112222SN/Adef rfind(l, elt, offs = -1):
11210417Sandreas.hansson@arm.com    for i in range(len(l)+offs, 0, -1):
11310417Sandreas.hansson@arm.com        if l[i] == elt:
1142147SN/A            return i
1152090SN/A    raise ValueError, "element not found"
1162147SN/A
1172090SN/A# helper function: compare dotted version numbers.
1182147SN/A# E.g., compare_version('1.3.25', '1.4.1')
1192147SN/A# returns -1, 0, 1 if v1 is <, ==, > v2
1202147SN/Adef compare_versions(v1, v2):
1212222SN/A    # Convert dotted strings to lists
1225569Snate@binkert.org    v1 = map(int, v1.split('.'))
1235569Snate@binkert.org    v2 = map(int, v2.split('.'))
1245569Snate@binkert.org    # Compare corresponding elements of lists
1255569Snate@binkert.org    for n1,n2 in zip(v1, v2):
1262112SN/A        if n1 < n2: return -1
1274695Sgblack@eecs.umich.edu        if n1 > n2: return  1
1282147SN/A    # all corresponding values are equal... see if one has extra values
1292222SN/A    if len(v1) < len(v2): return -1
1302147SN/A    if len(v1) > len(v2): return  1
1312090SN/A    return 0
1322502SN/A
1332502SN/A# Each target must have 'build' in the interior of the path; the
1344997Sgblack@eecs.umich.edu# directory below this will determine the build parameters.  For
1355568Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
1365736Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
1372502SN/A# follow 'build' in the bulid path.
1385569Snate@binkert.org
1392502SN/A# Generate absolute paths to targets so we can see where the build dir is
1405736Snate@binkert.orgif COMMAND_LINE_TARGETS:
1412502SN/A    # Ask SCons which directory it was invoked from
1422502SN/A    launch_dir = GetLaunchDir()
1434695Sgblack@eecs.umich.edu    # Make targets relative to invocation directory
1442502SN/A    abs_targets = map(lambda x: os.path.normpath(joinpath(launch_dir, str(x))),
1452502SN/A                      COMMAND_LINE_TARGETS)
14610417Sandreas.hansson@arm.comelse:
14710417Sandreas.hansson@arm.com    # Default targets are relative to root of tree
1482502SN/A    abs_targets = map(lambda x: os.path.normpath(joinpath(ROOT, str(x))),
1492502SN/A                      DEFAULT_TARGETS)
1502502SN/A
1512090SN/A
1522147SN/A# Generate a list of the unique build roots and configs that the
1532147SN/A# collected targets reference.
1542147SN/Abuild_paths = []
1552222SN/Abuild_root = None
1565569Snate@binkert.orgfor t in abs_targets:
1572112SN/A    path_dirs = t.split('/')
1585736Snate@binkert.org    try:
1592502SN/A        build_top = rfind(path_dirs, 'build', -2)
1602502SN/A    except:
1614695Sgblack@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
1622147SN/A        Exit(1)
1632222SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
16410417Sandreas.hansson@arm.com    if not build_root:
16510417Sandreas.hansson@arm.com        build_root = this_build_root
1662147SN/A    else:
1672090SN/A        if this_build_root != build_root:
1682502SN/A            print "Error: build targets not under same build root\n"\
1692090SN/A                  "  %s\n  %s" % (build_root, this_build_root)
1702147SN/A            Exit(1)
1712147SN/A    build_path = joinpath('/',*path_dirs[:build_top+2])
1722147SN/A    if build_path not in build_paths:
1732222SN/A        build_paths.append(build_path)
1745569Snate@binkert.org
1752112SN/A###################################################
1765736Snate@binkert.org#
1772502SN/A# Set up the default build environment.  This environment is copied
1782502SN/A# and modified according to each selected configuration.
1794695Sgblack@eecs.umich.edu#
1802147SN/A###################################################
1812222SN/A
1822147SN/Aenv = Environment(ENV = os.environ,  # inherit user's environment vars
1832090SN/A                  ROOT = ROOT,
1842502SN/A                  SRCDIR = SRCDIR)
1852090SN/A
1862147SN/A#Parse CC/CXX early so that we use the correct compiler for 
1872147SN/A# to test for dependencies/versions/libraries/includes
1882147SN/Aif ARGUMENTS.get('CC', None):
1892222SN/A    env['CC'] = ARGUMENTS.get('CC')
1905569Snate@binkert.org
1912112SN/Aif ARGUMENTS.get('CXX', None):
1925736Snate@binkert.org    env['CXX'] = ARGUMENTS.get('CXX')
1932502SN/A
1942502SN/Aenv.SConsignFile(joinpath(build_root,"sconsign"))
1954695Sgblack@eecs.umich.edu
1962147SN/A# Default duplicate option is to use hard links, but this messes up
1972222SN/A# when you use emacs to edit a file in the target dir, as emacs moves
1982147SN/A# file to file~ then copies to file, breaking the link.  Symbolic
1992090SN/A# (soft) links work better.
2002502SN/Aenv.SetOption('duplicate', 'soft-copy')
2012090SN/A
2022147SN/A# I waffle on this setting... it does avoid a few painful but
2032147SN/A# unnecessary builds, but it also seems to make trivial builds take
2042147SN/A# noticeably longer.
2052222SN/Aif False:
2065569Snate@binkert.org    env.TargetSignatures('content')
2072112SN/A
2085736Snate@binkert.org# M5_PLY is used by isa_parser.py to find the PLY package.
2092502SN/Aenv.Append(ENV = { 'M5_PLY' : Dir('ext/ply') })
2102502SN/Aenv['GCC'] = False
2114695Sgblack@eecs.umich.eduenv['SUNCC'] = False
2122147SN/Aenv['ICC'] = False
2132222SN/Aenv['GCC'] = subprocess.Popen(env['CXX'] + ' --version', shell=True, 
2142147SN/A        stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 
2152090SN/A        close_fds=True).communicate()[0].find('GCC') >= 0
2162502SN/Aenv['SUNCC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True, 
2172090SN/A        stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 
2182147SN/A        close_fds=True).communicate()[0].find('Sun C++') >= 0
2192147SN/Aenv['ICC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True, 
2202147SN/A        stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 
2212222SN/A        close_fds=True).communicate()[0].find('Intel') >= 0
2225569Snate@binkert.orgif env['GCC'] + env['SUNCC'] env['ICC'] > 1:
2232112SN/A    print 'Error: How can we have two at the same time?'
2245736Snate@binkert.org    Exit(1)
2252502SN/A
2262502SN/A
2274695Sgblack@eecs.umich.edu# Set up default C++ compiler flags
2282147SN/Aif env['GCC']:
2292222SN/A    env.Append(CCFLAGS='-pipe')
2302147SN/A    env.Append(CCFLAGS='-fno-strict-aliasing')
2312090SN/A    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
2322502SN/Aelif env['ICC']:
2332502SN/A    pass #Fix me... add warning flags once we clean up icc warnings
2344997Sgblack@eecs.umich.eduelif env['SUNCC']:
2352502SN/A    env.Append(CCFLAGS='-Qoption ccfe')
2365569Snate@binkert.org    env.Append(CCFLAGS='-features=gcc')
2372502SN/A    env.Append(CCFLAGS='-features=extensions')
2385569Snate@binkert.org    env.Append(CCFLAGS='-library=stlport4')
2394695Sgblack@eecs.umich.edu    env.Append(CCFLAGS='-xar')
2402505SN/A#    env.Append(CCFLAGS='-instances=semiexplicit')
2412505SN/Aelse:
24210417Sandreas.hansson@arm.com    print 'Error: Don\'t know what compiler options to use for your compiler.'
24310417Sandreas.hansson@arm.com    print '       Please fix SConstruct and src/SConscript and try again.'
2442502SN/A    Exit(1)
2452502SN/A
2462502SN/Aif sys.platform == 'cygwin':
2472090SN/A    # cygwin has some header file issues...
2482147SN/A    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
2492147SN/Aenv.Append(CPPPATH=[Dir('ext/dnet')])
2502147SN/A
2512222SN/A# Check for SWIG
2525569Snate@binkert.orgif not env.has_key('SWIG'):
2532112SN/A    print 'Error: SWIG utility not found.'
2545569Snate@binkert.org    print '       Please install (see http://www.swig.org) and retry.'
2554695Sgblack@eecs.umich.edu    Exit(1)
2562502SN/A
2572502SN/A# Check for appropriate SWIG version
25810417Sandreas.hansson@arm.comswig_version = os.popen('swig -version').read().split()
25910417Sandreas.hansson@arm.com# First 3 words should be "SWIG Version x.y.z"
2602502SN/Aif swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
2612502SN/A    print 'Error determining SWIG version.'
2622502SN/A    Exit(1)
2632502SN/A
2642502SN/Amin_swig_version = '1.3.28'
2652502SN/Aif compare_versions(swig_version[2], min_swig_version) < 0:
2662502SN/A    print 'Error: SWIG version', min_swig_version, 'or newer required.'
2672502SN/A    print '       Installed version:', swig_version[2]
2685569Snate@binkert.org    Exit(1)
2692502SN/A
2705569Snate@binkert.org# Set up SWIG flags & scanner
2714695Sgblack@eecs.umich.eduenv.Append(SWIGFLAGS=Split('-c++ -python -modern $_CPPINCFLAGS'))
2722147SN/A
2732222SN/Aimport SCons.Scanner
2742147SN/A
2752090SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
2762147SN/A
2772090SN/Aswig_scanner = SCons.Scanner.ClassicCPP("SwigScan", ".i", "CPPPATH",
2782147SN/A                                        swig_inc_re)
2792147SN/A
2802147SN/Aenv.Append(SCANNERS = swig_scanner)
2812222SN/A
2825569Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
2832112SN/A# builds under a given build root run on the same host platform.
2844695Sgblack@eecs.umich.educonf = Configure(env,
2852147SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
2862222SN/A                 log_file = joinpath(build_root, 'scons_config.log'))
2872147SN/A
2882090SN/A# Find Python include and library directories for embedding the
2892147SN/A# interpreter.  For consistency, we will use the same Python
2902090SN/A# installation used to run scons (and thus this script).  If you want
2912147SN/A# to link in an alternate version, see above for instructions on how
2922147SN/A# to invoke scons with a different copy of the Python interpreter.
2932147SN/A
2942222SN/A# Get brief Python version name (e.g., "python2.4") for locating
2955569Snate@binkert.org# include & library files
2962112SN/Apy_version_name = 'python' + sys.version[:3]
2974695Sgblack@eecs.umich.edu
2982147SN/A# include path, e.g. /usr/local/include/python2.4
2992222SN/Apy_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
3002147SN/Aenv.Append(CPPPATH = py_header_path)
3012090SN/A# verify that it works
30212110SRekai.GonzalezAlberquilla@arm.comif not conf.CheckHeader('Python.h', '<>'):
30312110SRekai.GonzalezAlberquilla@arm.com    print "Error: can't find Python.h header in", py_header_path
30412110SRekai.GonzalezAlberquilla@arm.com    Exit(1)
30512110SRekai.GonzalezAlberquilla@arm.com
30612110SRekai.GonzalezAlberquilla@arm.com# add library path too if it's not in the default place
30712110SRekai.GonzalezAlberquilla@arm.compy_lib_path = None
30812110SRekai.GonzalezAlberquilla@arm.comif sys.exec_prefix != '/usr':
30912110SRekai.GonzalezAlberquilla@arm.com    py_lib_path = joinpath(sys.exec_prefix, 'lib')
31012110SRekai.GonzalezAlberquilla@arm.comelif sys.platform == 'cygwin':
31112110SRekai.GonzalezAlberquilla@arm.com    # cygwin puts the .dll in /bin for some reason
31212110SRekai.GonzalezAlberquilla@arm.com    py_lib_path = '/bin'
31312110SRekai.GonzalezAlberquilla@arm.comif py_lib_path:
31412110SRekai.GonzalezAlberquilla@arm.com    env.Append(LIBPATH = py_lib_path)
3152147SN/A    print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
3162090SN/Aif not conf.CheckLib(py_version_name):
3172147SN/A    print "Error: can't find Python library", py_version_name
3182147SN/A    Exit(1)
3192147SN/A
3202222SN/A# On Solaris you need to use libsocket for socket ops
3215569Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
3225569Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
3235569Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
3245569Snate@binkert.org       Exit(1)
3252112SN/A
3264695Sgblack@eecs.umich.edu# Check for zlib.  If the check passes, libz will be automatically
3272147SN/A# added to the LIBS environment variable.
3282222SN/Aif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
3292147SN/A    print 'Error: did not find needed zlib compression library '\
3302090SN/A          'and/or zlib.h header file.'
3312147SN/A    print '       Please install zlib and try again.'
3322090SN/A    Exit(1)
3332147SN/A
3342147SN/A# Check for <fenv.h> (C99 FP environment control)
3352147SN/Ahave_fenv = conf.CheckHeader('fenv.h', '<>')
3362222SN/Aif not have_fenv:
3375569Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
3382112SN/A    print "         This host has no IEEE FP rounding mode control."
3394695Sgblack@eecs.umich.edu
3402147SN/A# Check for mysql.
3412222SN/Amysql_config = WhereIs('mysql_config')
3422147SN/Ahave_mysql = mysql_config != None
3432090SN/A
3445569Snate@binkert.org# Check MySQL version.
3452167SN/Aif have_mysql:
3465569Snate@binkert.org    mysql_version = os.popen(mysql_config + ' --version').read()
347    min_mysql_version = '4.1'
348    if compare_versions(mysql_version, min_mysql_version) < 0:
349        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
350        print '         Version', mysql_version, 'detected.'
351        have_mysql = False
352
353# Set up mysql_config commands.
354if have_mysql:
355    mysql_config_include = mysql_config + ' --include'
356    if os.system(mysql_config_include + ' > /dev/null') != 0:
357        # older mysql_config versions don't support --include, use
358        # --cflags instead
359        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
360    # This seems to work in all versions
361    mysql_config_libs = mysql_config + ' --libs'
362
363env = conf.Finish()
364
365# Define the universe of supported ISAs
366env['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
367
368# Define the universe of supported CPU models
369env['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
370                       'O3CPU', 'OzoneCPU']
371
372if os.path.isdir(joinpath(SRCDIR, 'encumbered/cpu/full')):
373    env['ALL_CPU_LIST'] += ['FullCPU']
374
375# Sticky options get saved in the options file so they persist from
376# one invocation to the next (unless overridden, in which case the new
377# value becomes sticky).
378sticky_opts = Options(args=ARGUMENTS)
379sticky_opts.AddOptions(
380    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env['ALL_ISA_LIST']),
381    BoolOption('FULL_SYSTEM', 'Full-system support', False),
382    # There's a bug in scons 0.96.1 that causes ListOptions with list
383    # values (more than one value) not to be able to be restored from
384    # a saved option file.  If this causes trouble then upgrade to
385    # scons 0.96.90 or later.
386    ListOption('CPU_MODELS', 'CPU models', 'AtomicSimpleCPU,TimingSimpleCPU,O3CPU',
387               env['ALL_CPU_LIST']),
388    BoolOption('ALPHA_TLASER',
389               'Model Alpha TurboLaser platform (vs. Tsunami)', False),
390    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
391    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
392               False),
393    BoolOption('SS_COMPATIBLE_FP',
394               'Make floating-point results compatible with SimpleScalar',
395               False),
396    BoolOption('USE_SSE2',
397               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
398               False),
399    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
400    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
401    BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
402    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
403    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
404    BoolOption('BATCH', 'Use batch pool for build and tests', False),
405    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
406    ('PYTHONHOME',
407     'Override the default PYTHONHOME for this system (use with caution)',
408     '%s:%s' % (sys.prefix, sys.exec_prefix))
409    )
410
411# Non-sticky options only apply to the current build.
412nonsticky_opts = Options(args=ARGUMENTS)
413nonsticky_opts.AddOptions(
414    BoolOption('update_ref', 'Update test reference outputs', False)
415    )
416
417# These options get exported to #defines in config/*.hh (see src/SConscript).
418env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
419                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
420                     'USE_CHECKER', 'PYTHONHOME', 'TARGET_ISA']
421
422# Define a handy 'no-op' action
423def no_action(target, source, env):
424    return 0
425
426env.NoAction = Action(no_action, None)
427
428###################################################
429#
430# Define a SCons builder for configuration flag headers.
431#
432###################################################
433
434# This function generates a config header file that #defines the
435# option symbol to the current option setting (0 or 1).  The source
436# operands are the name of the option and a Value node containing the
437# value of the option.
438def build_config_file(target, source, env):
439    (option, value) = [s.get_contents() for s in source]
440    f = file(str(target[0]), 'w')
441    print >> f, '#define', option, value
442    f.close()
443    return None
444
445# Generate the message to be printed when building the config file.
446def build_config_file_string(target, source, env):
447    (option, value) = [s.get_contents() for s in source]
448    return "Defining %s as %s in %s." % (option, value, target[0])
449
450# Combine the two functions into a scons Action object.
451config_action = Action(build_config_file, build_config_file_string)
452
453# The emitter munges the source & target node lists to reflect what
454# we're really doing.
455def config_emitter(target, source, env):
456    # extract option name from Builder arg
457    option = str(target[0])
458    # True target is config header file
459    target = joinpath('config', option.lower() + '.hh')
460    val = env[option]
461    if isinstance(val, bool):
462        # Force value to 0/1
463        val = int(val)
464    elif isinstance(val, str):
465        val = '"' + val + '"'
466        
467    # Sources are option name & value (packaged in SCons Value nodes)
468    return ([target], [Value(option), Value(val)])
469
470config_builder = Builder(emitter = config_emitter, action = config_action)
471
472env.Append(BUILDERS = { 'ConfigFile' : config_builder })
473
474###################################################
475#
476# Define a SCons builder for copying files.  This is used by the
477# Python zipfile code in src/python/SConscript, but is placed up here
478# since it's potentially more generally applicable.
479#
480###################################################
481
482copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
483
484env.Append(BUILDERS = { 'CopyFile' : copy_builder })
485
486###################################################
487#
488# Define a simple SCons builder to concatenate files.
489#
490# Used to append the Python zip archive to the executable.
491#
492###################################################
493
494concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
495                                          'chmod +x $TARGET']))
496
497env.Append(BUILDERS = { 'Concat' : concat_builder })
498
499
500# base help text
501help_text = '''
502Usage: scons [scons options] [build options] [target(s)]
503
504'''
505
506# libelf build is shared across all configs in the build root.
507env.SConscript('ext/libelf/SConscript',
508               build_dir = joinpath(build_root, 'libelf'),
509               exports = 'env')
510
511###################################################
512#
513# This function is used to set up a directory with switching headers
514#
515###################################################
516
517def make_switching_dir(dirname, switch_headers, env):
518    # Generate the header.  target[0] is the full path of the output
519    # header to generate.  'source' is a dummy variable, since we get the
520    # list of ISAs from env['ALL_ISA_LIST'].
521    def gen_switch_hdr(target, source, env):
522	fname = str(target[0])
523	basename = os.path.basename(fname)
524	f = open(fname, 'w')
525	f.write('#include "arch/isa_specific.hh"\n')
526	cond = '#if'
527	for isa in env['ALL_ISA_LIST']:
528	    f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
529		    % (cond, isa.upper(), dirname, isa, basename))
530	    cond = '#elif'
531	f.write('#else\n#error "THE_ISA not set"\n#endif\n')
532	f.close()
533	return 0
534
535    # String to print when generating header
536    def gen_switch_hdr_string(target, source, env):
537	return "Generating switch header " + str(target[0])
538
539    # Build SCons Action object. 'varlist' specifies env vars that this
540    # action depends on; when env['ALL_ISA_LIST'] changes these actions
541    # should get re-executed.
542    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
543                               varlist=['ALL_ISA_LIST'])
544
545    # Instantiate actions for each header
546    for hdr in switch_headers:
547        env.Command(hdr, [], switch_hdr_action)
548
549env.make_switching_dir = make_switching_dir
550
551###################################################
552#
553# Define build environments for selected configurations.
554#
555###################################################
556
557# rename base env
558base_env = env
559
560for build_path in build_paths:
561    print "Building in", build_path
562    # build_dir is the tail component of build path, and is used to
563    # determine the build parameters (e.g., 'ALPHA_SE')
564    (build_root, build_dir) = os.path.split(build_path)
565    # Make a copy of the build-root environment to use for this config.
566    env = base_env.Copy()
567
568    # Set env options according to the build directory config.
569    sticky_opts.files = []
570    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
571    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
572    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
573    current_opts_file = joinpath(build_root, 'options', build_dir)
574    if os.path.isfile(current_opts_file):
575        sticky_opts.files.append(current_opts_file)
576        print "Using saved options file %s" % current_opts_file
577    else:
578        # Build dir-specific options file doesn't exist.
579
580        # Make sure the directory is there so we can create it later
581        opt_dir = os.path.dirname(current_opts_file)
582        if not os.path.isdir(opt_dir):
583            os.mkdir(opt_dir)
584
585        # Get default build options from source tree.  Options are
586        # normally determined by name of $BUILD_DIR, but can be
587        # overriden by 'default=' arg on command line.
588        default_opts_file = joinpath('build_opts',
589                                     ARGUMENTS.get('default', build_dir))
590        if os.path.isfile(default_opts_file):
591            sticky_opts.files.append(default_opts_file)
592            print "Options file %s not found,\n  using defaults in %s" \
593                  % (current_opts_file, default_opts_file)
594        else:
595            print "Error: cannot find options file %s or %s" \
596                  % (current_opts_file, default_opts_file)
597            Exit(1)
598
599    # Apply current option settings to env
600    sticky_opts.Update(env)
601    nonsticky_opts.Update(env)
602
603    help_text += "Sticky options for %s:\n" % build_dir \
604                 + sticky_opts.GenerateHelpText(env) \
605                 + "\nNon-sticky options for %s:\n" % build_dir \
606                 + nonsticky_opts.GenerateHelpText(env)
607
608    # Process option settings.
609
610    if not have_fenv and env['USE_FENV']:
611        print "Warning: <fenv.h> not available; " \
612              "forcing USE_FENV to False in", build_dir + "."
613        env['USE_FENV'] = False
614
615    if not env['USE_FENV']:
616        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
617        print "         FP results may deviate slightly from other platforms."
618
619    if env['EFENCE']:
620        env.Append(LIBS=['efence'])
621
622    if env['USE_MYSQL']:
623        if not have_mysql:
624            print "Warning: MySQL not available; " \
625                  "forcing USE_MYSQL to False in", build_dir + "."
626            env['USE_MYSQL'] = False
627        else:
628            print "Compiling in", build_dir, "with MySQL support."
629            env.ParseConfig(mysql_config_libs)
630            env.ParseConfig(mysql_config_include)
631
632    # Save sticky option settings back to current options file
633    sticky_opts.Save(current_opts_file, env)
634
635    # Do this after we save setting back, or else we'll tack on an
636    # extra 'qdo' every time we run scons.
637    if env['BATCH']:
638        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
639        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
640
641    if env['USE_SSE2']:
642        env.Append(CCFLAGS='-msse2')
643
644    # The src/SConscript file sets up the build rules in 'env' according
645    # to the configured options.  It returns a list of environments,
646    # one for each variant build (debug, opt, etc.)
647    envList = SConscript('src/SConscript', build_dir = build_path,
648                         exports = 'env')
649
650    # Set up the regression tests for each build.
651    for e in envList:
652        SConscript('tests/SConscript',
653                   build_dir = joinpath(build_path, 'tests', e.Label),
654                   exports = { 'env' : e }, duplicate = False)
655
656Help(help_text)
657
658
659###################################################
660#
661# Let SCons do its thing.  At this point SCons will use the defined
662# build environments to build the requested targets.
663#
664###################################################
665
666