SConstruct revision 5204
1# -*- mode:python -*-
2
3# Copyright (c) 2004-2005 The Regents of The University of Michigan
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met: redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer;
10# redistributions in binary form must reproduce the above copyright
11# notice, this list of conditions and the following disclaimer in the
12# documentation and/or other materials provided with the distribution;
13# neither the name of the copyright holders nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28#
29# Authors: Steve Reinhardt
30
31###################################################
32#
33# SCons top-level build description (SConstruct) file.
34#
35# While in this directory ('m5'), just type 'scons' to build the default
36# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
37# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
38# the optimized full-system version).
39#
40# You can build M5 in a different directory as long as there is a
41# 'build/<CONFIG>' somewhere along the target path.  The build system
42# expects that all configs under the same build directory are being
43# built for the same host system.
44#
45# Examples:
46#
47#   The following two commands are equivalent.  The '-u' option tells
48#   scons to search up the directory tree for this SConstruct file.
49#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
50#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
51#
52#   The following two commands are equivalent and demonstrate building
53#   in a directory outside of the source tree.  The '-C' option tells
54#   scons to chdir to the specified directory to find this SConstruct
55#   file.
56#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
57#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
58#
59# You can use 'scons -H' to print scons options.  If you're in this
60# 'm5' directory (or use -u or -C to tell scons where to find this
61# file), you can use 'scons -h' to print all the M5-specific build
62# options as well.
63#
64###################################################
65
66import sys
67import os
68import subprocess
69
70from os.path import isdir, join as joinpath
71
72# Check for recent-enough Python and SCons versions.  If your system's
73# default installation of Python is not recent enough, you can use a
74# non-default installation of the Python interpreter by either (1)
75# rearranging your PATH so that scons finds the non-default 'python'
76# first or (2) explicitly invoking an alternative interpreter on the
77# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
78EnsurePythonVersion(2,4)
79
80# Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
81# 3-element version number.
82min_scons_version = (0,96,91)
83try:
84    EnsureSConsVersion(*min_scons_version)
85except:
86    print "Error checking current SCons version."
87    print "SCons", ".".join(map(str,min_scons_version)), "or greater required."
88    Exit(2)
89
90
91# The absolute path to the current directory (where this file lives).
92ROOT = Dir('.').abspath
93
94# Path to the M5 source tree.
95SRCDIR = joinpath(ROOT, 'src')
96
97# tell python where to find m5 python code
98sys.path.append(joinpath(ROOT, 'src/python'))
99
100def check_style_hook(ui):
101    ui.readconfig(joinpath(ROOT, '.hg', 'hgrc'))
102    style_hook = ui.config('hooks', 'pretxncommit.style', None)
103
104    if not style_hook:
105        print """\
106You're missing the M5 style hook.
107Please install the hook so we can ensure that all code fits a common style.
108
109All you'd need to do is add the following lines to your repository .hg/hgrc
110or your personal .hgrc
111----------------
112
113[extensions]
114style = %s/util/style.py
115
116[hooks]
117pretxncommit.style = python:style.check_whitespace
118""" % (ROOT)
119        sys.exit(1)
120
121if ARGUMENTS.get('IGNORE_STYLE') != 'True' and isdir(joinpath(ROOT, '.hg')):
122    try:
123        from mercurial import ui
124        check_style_hook(ui.ui())
125    except ImportError:
126        pass
127
128###################################################
129#
130# Figure out which configurations to set up based on the path(s) of
131# the target(s).
132#
133###################################################
134
135# Find default configuration & binary.
136Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
137
138# helper function: find last occurrence of element in list
139def rfind(l, elt, offs = -1):
140    for i in range(len(l)+offs, 0, -1):
141        if l[i] == elt:
142            return i
143    raise ValueError, "element not found"
144
145# helper function: compare dotted version numbers.
146# E.g., compare_version('1.3.25', '1.4.1')
147# returns -1, 0, 1 if v1 is <, ==, > v2
148def compare_versions(v1, v2):
149    # Convert dotted strings to lists
150    v1 = map(int, v1.split('.'))
151    v2 = map(int, v2.split('.'))
152    # Compare corresponding elements of lists
153    for n1,n2 in zip(v1, v2):
154        if n1 < n2: return -1
155        if n1 > n2: return  1
156    # all corresponding values are equal... see if one has extra values
157    if len(v1) < len(v2): return -1
158    if len(v1) > len(v2): return  1
159    return 0
160
161# Each target must have 'build' in the interior of the path; the
162# directory below this will determine the build parameters.  For
163# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
164# recognize that ALPHA_SE specifies the configuration because it
165# follow 'build' in the bulid path.
166
167# Generate absolute paths to targets so we can see where the build dir is
168if COMMAND_LINE_TARGETS:
169    # Ask SCons which directory it was invoked from
170    launch_dir = GetLaunchDir()
171    # Make targets relative to invocation directory
172    abs_targets = map(lambda x: os.path.normpath(joinpath(launch_dir, str(x))),
173                      COMMAND_LINE_TARGETS)
174else:
175    # Default targets are relative to root of tree
176    abs_targets = map(lambda x: os.path.normpath(joinpath(ROOT, str(x))),
177                      DEFAULT_TARGETS)
178
179
180# Generate a list of the unique build roots and configs that the
181# collected targets reference.
182build_paths = []
183build_root = None
184for t in abs_targets:
185    path_dirs = t.split('/')
186    try:
187        build_top = rfind(path_dirs, 'build', -2)
188    except:
189        print "Error: no non-leaf 'build' dir found on target path", t
190        Exit(1)
191    this_build_root = joinpath('/',*path_dirs[:build_top+1])
192    if not build_root:
193        build_root = this_build_root
194    else:
195        if this_build_root != build_root:
196            print "Error: build targets not under same build root\n"\
197                  "  %s\n  %s" % (build_root, this_build_root)
198            Exit(1)
199    build_path = joinpath('/',*path_dirs[:build_top+2])
200    if build_path not in build_paths:
201        build_paths.append(build_path)
202
203###################################################
204#
205# Set up the default build environment.  This environment is copied
206# and modified according to each selected configuration.
207#
208###################################################
209
210env = Environment(ENV = os.environ,  # inherit user's environment vars
211                  ROOT = ROOT,
212                  SRCDIR = SRCDIR)
213
214#Parse CC/CXX early so that we use the correct compiler for
215# to test for dependencies/versions/libraries/includes
216if ARGUMENTS.get('CC', None):
217    env['CC'] = ARGUMENTS.get('CC')
218
219if ARGUMENTS.get('CXX', None):
220    env['CXX'] = ARGUMENTS.get('CXX')
221
222Export('env')
223
224env.SConsignFile(joinpath(build_root,"sconsign"))
225
226# Default duplicate option is to use hard links, but this messes up
227# when you use emacs to edit a file in the target dir, as emacs moves
228# file to file~ then copies to file, breaking the link.  Symbolic
229# (soft) links work better.
230env.SetOption('duplicate', 'soft-copy')
231
232# I waffle on this setting... it does avoid a few painful but
233# unnecessary builds, but it also seems to make trivial builds take
234# noticeably longer.
235if False:
236    env.TargetSignatures('content')
237
238# M5_PLY is used by isa_parser.py to find the PLY package.
239env.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
240env['GCC'] = False
241env['SUNCC'] = False
242env['ICC'] = False
243env['GCC'] = subprocess.Popen(env['CXX'] + ' --version', shell=True,
244        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
245        close_fds=True).communicate()[0].find('GCC') >= 0
246env['SUNCC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
247        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
248        close_fds=True).communicate()[0].find('Sun C++') >= 0
249env['ICC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
250        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
251        close_fds=True).communicate()[0].find('Intel') >= 0
252if env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
253    print 'Error: How can we have two at the same time?'
254    Exit(1)
255
256
257# Set up default C++ compiler flags
258if env['GCC']:
259    env.Append(CCFLAGS='-pipe')
260    env.Append(CCFLAGS='-fno-strict-aliasing')
261    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
262elif env['ICC']:
263    pass #Fix me... add warning flags once we clean up icc warnings
264elif env['SUNCC']:
265    env.Append(CCFLAGS='-Qoption ccfe')
266    env.Append(CCFLAGS='-features=gcc')
267    env.Append(CCFLAGS='-features=extensions')
268    env.Append(CCFLAGS='-library=stlport4')
269    env.Append(CCFLAGS='-xar')
270#    env.Append(CCFLAGS='-instances=semiexplicit')
271else:
272    print 'Error: Don\'t know what compiler options to use for your compiler.'
273    print '       Please fix SConstruct and src/SConscript and try again.'
274    Exit(1)
275
276if sys.platform == 'cygwin':
277    # cygwin has some header file issues...
278    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
279env.Append(CPPPATH=[Dir('ext/dnet')])
280
281# Check for SWIG
282if not env.has_key('SWIG'):
283    print 'Error: SWIG utility not found.'
284    print '       Please install (see http://www.swig.org) and retry.'
285    Exit(1)
286
287# Check for appropriate SWIG version
288swig_version = os.popen('swig -version').read().split()
289# First 3 words should be "SWIG Version x.y.z"
290if len(swig_version) < 3 or \
291        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
292    print 'Error determining SWIG version.'
293    Exit(1)
294
295min_swig_version = '1.3.28'
296if compare_versions(swig_version[2], min_swig_version) < 0:
297    print 'Error: SWIG version', min_swig_version, 'or newer required.'
298    print '       Installed version:', swig_version[2]
299    Exit(1)
300
301# Set up SWIG flags & scanner
302swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
303env.Append(SWIGFLAGS=swig_flags)
304
305# filter out all existing swig scanners, they mess up the dependency
306# stuff for some reason
307scanners = []
308for scanner in env['SCANNERS']:
309    skeys = scanner.skeys
310    if skeys == '.i':
311        continue
312
313    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
314        continue
315
316    scanners.append(scanner)
317
318# add the new swig scanner that we like better
319from SCons.Scanner import ClassicCPP as CPPScanner
320swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
321scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
322
323# replace the scanners list that has what we want
324env['SCANNERS'] = scanners
325
326# Platform-specific configuration.  Note again that we assume that all
327# builds under a given build root run on the same host platform.
328conf = Configure(env,
329                 conf_dir = joinpath(build_root, '.scons_config'),
330                 log_file = joinpath(build_root, 'scons_config.log'))
331
332# Recent versions of scons substitute a "Null" object for Configure()
333# when configuration isn't necessary, e.g., if the "--help" option is
334# present.  Unfortuantely this Null object always returns false,
335# breaking all our configuration checks.  We replace it with our own
336# more optimistic null object that returns True instead.
337if not conf:
338    def NullCheck(*args, **kwargs):
339        return True
340
341    class NullConf:
342        def __init__(self, env):
343            self.env = env
344        def Finish(self):
345            return self.env
346        def __getattr__(self, mname):
347            return NullCheck
348
349    conf = NullConf(env)
350
351# Find Python include and library directories for embedding the
352# interpreter.  For consistency, we will use the same Python
353# installation used to run scons (and thus this script).  If you want
354# to link in an alternate version, see above for instructions on how
355# to invoke scons with a different copy of the Python interpreter.
356
357# Get brief Python version name (e.g., "python2.4") for locating
358# include & library files
359py_version_name = 'python' + sys.version[:3]
360
361# include path, e.g. /usr/local/include/python2.4
362py_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
363env.Append(CPPPATH = py_header_path)
364# verify that it works
365if not conf.CheckHeader('Python.h', '<>'):
366    print "Error: can't find Python.h header in", py_header_path
367    Exit(1)
368
369# add library path too if it's not in the default place
370py_lib_path = None
371if sys.exec_prefix != '/usr':
372    py_lib_path = joinpath(sys.exec_prefix, 'lib')
373elif sys.platform == 'cygwin':
374    # cygwin puts the .dll in /bin for some reason
375    py_lib_path = '/bin'
376if py_lib_path:
377    env.Append(LIBPATH = py_lib_path)
378    print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
379if not conf.CheckLib(py_version_name):
380    print "Error: can't find Python library", py_version_name
381    Exit(1)
382
383# On Solaris you need to use libsocket for socket ops
384if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
385   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
386       print "Can't find library with socket calls (e.g. accept())"
387       Exit(1)
388
389# Check for zlib.  If the check passes, libz will be automatically
390# added to the LIBS environment variable.
391if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
392    print 'Error: did not find needed zlib compression library '\
393          'and/or zlib.h header file.'
394    print '       Please install zlib and try again.'
395    Exit(1)
396
397# Check for <fenv.h> (C99 FP environment control)
398have_fenv = conf.CheckHeader('fenv.h', '<>')
399if not have_fenv:
400    print "Warning: Header file <fenv.h> not found."
401    print "         This host has no IEEE FP rounding mode control."
402
403# Check for mysql.
404mysql_config = WhereIs('mysql_config')
405have_mysql = mysql_config != None
406
407# Check MySQL version.
408if have_mysql:
409    mysql_version = os.popen(mysql_config + ' --version').read()
410    min_mysql_version = '4.1'
411    if compare_versions(mysql_version, min_mysql_version) < 0:
412        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
413        print '         Version', mysql_version, 'detected.'
414        have_mysql = False
415
416# Set up mysql_config commands.
417if have_mysql:
418    mysql_config_include = mysql_config + ' --include'
419    if os.system(mysql_config_include + ' > /dev/null') != 0:
420        # older mysql_config versions don't support --include, use
421        # --cflags instead
422        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
423    # This seems to work in all versions
424    mysql_config_libs = mysql_config + ' --libs'
425
426env = conf.Finish()
427
428# Define the universe of supported ISAs
429all_isa_list = [ ]
430Export('all_isa_list')
431
432# Define the universe of supported CPU models
433all_cpu_list = [ ]
434default_cpus = [ ]
435Export('all_cpu_list', 'default_cpus')
436
437# Sticky options get saved in the options file so they persist from
438# one invocation to the next (unless overridden, in which case the new
439# value becomes sticky).
440sticky_opts = Options(args=ARGUMENTS)
441Export('sticky_opts')
442
443# Non-sticky options only apply to the current build.
444nonsticky_opts = Options(args=ARGUMENTS)
445Export('nonsticky_opts')
446
447# Walk the tree and execute all SConsopts scripts that wil add to the
448# above options
449for root, dirs, files in os.walk('.'):
450    if 'SConsopts' in files:
451        SConscript(os.path.join(root, 'SConsopts'))
452
453all_isa_list.sort()
454all_cpu_list.sort()
455default_cpus.sort()
456
457def ExtraPathValidator(key, val, env):
458    if not val:
459        return
460    paths = val.split(':')
461    for path in paths:
462        path = os.path.expanduser(path)
463        if not isdir(path):
464            raise AttributeError, "Invalid path: '%s'" % path
465
466sticky_opts.AddOptions(
467    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
468    BoolOption('FULL_SYSTEM', 'Full-system support', False),
469    # There's a bug in scons 0.96.1 that causes ListOptions with list
470    # values (more than one value) not to be able to be restored from
471    # a saved option file.  If this causes trouble then upgrade to
472    # scons 0.96.90 or later.
473    ListOption('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
474    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
475    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
476               False),
477    BoolOption('SS_COMPATIBLE_FP',
478               'Make floating-point results compatible with SimpleScalar',
479               False),
480    BoolOption('USE_SSE2',
481               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
482               False),
483    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
484    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
485    BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
486    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
487    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
488    BoolOption('BATCH', 'Use batch pool for build and tests', False),
489    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
490    ('PYTHONHOME',
491     'Override the default PYTHONHOME for this system (use with caution)',
492     '%s:%s' % (sys.prefix, sys.exec_prefix)),
493    ('EXTRAS', 'Add Extra directories to the compilation', '',
494     ExtraPathValidator)
495    )
496
497nonsticky_opts.AddOptions(
498    BoolOption('update_ref', 'Update test reference outputs', False)
499    )
500
501# These options get exported to #defines in config/*.hh (see src/SConscript).
502env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
503                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
504                     'USE_CHECKER', 'PYTHONHOME', 'TARGET_ISA']
505
506# Define a handy 'no-op' action
507def no_action(target, source, env):
508    return 0
509
510env.NoAction = Action(no_action, None)
511
512###################################################
513#
514# Define a SCons builder for configuration flag headers.
515#
516###################################################
517
518# This function generates a config header file that #defines the
519# option symbol to the current option setting (0 or 1).  The source
520# operands are the name of the option and a Value node containing the
521# value of the option.
522def build_config_file(target, source, env):
523    (option, value) = [s.get_contents() for s in source]
524    f = file(str(target[0]), 'w')
525    print >> f, '#define', option, value
526    f.close()
527    return None
528
529# Generate the message to be printed when building the config file.
530def build_config_file_string(target, source, env):
531    (option, value) = [s.get_contents() for s in source]
532    return "Defining %s as %s in %s." % (option, value, target[0])
533
534# Combine the two functions into a scons Action object.
535config_action = Action(build_config_file, build_config_file_string)
536
537# The emitter munges the source & target node lists to reflect what
538# we're really doing.
539def config_emitter(target, source, env):
540    # extract option name from Builder arg
541    option = str(target[0])
542    # True target is config header file
543    target = joinpath('config', option.lower() + '.hh')
544    val = env[option]
545    if isinstance(val, bool):
546        # Force value to 0/1
547        val = int(val)
548    elif isinstance(val, str):
549        val = '"' + val + '"'
550
551    # Sources are option name & value (packaged in SCons Value nodes)
552    return ([target], [Value(option), Value(val)])
553
554config_builder = Builder(emitter = config_emitter, action = config_action)
555
556env.Append(BUILDERS = { 'ConfigFile' : config_builder })
557
558###################################################
559#
560# Define a SCons builder for copying files.  This is used by the
561# Python zipfile code in src/python/SConscript, but is placed up here
562# since it's potentially more generally applicable.
563#
564###################################################
565
566copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
567
568env.Append(BUILDERS = { 'CopyFile' : copy_builder })
569
570###################################################
571#
572# Define a simple SCons builder to concatenate files.
573#
574# Used to append the Python zip archive to the executable.
575#
576###################################################
577
578concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
579                                          'chmod +x $TARGET']))
580
581env.Append(BUILDERS = { 'Concat' : concat_builder })
582
583
584# base help text
585help_text = '''
586Usage: scons [scons options] [build options] [target(s)]
587
588'''
589
590# libelf build is shared across all configs in the build root.
591env.SConscript('ext/libelf/SConscript',
592               build_dir = joinpath(build_root, 'libelf'),
593               exports = 'env')
594
595###################################################
596#
597# This function is used to set up a directory with switching headers
598#
599###################################################
600
601env['ALL_ISA_LIST'] = all_isa_list
602def make_switching_dir(dirname, switch_headers, env):
603    # Generate the header.  target[0] is the full path of the output
604    # header to generate.  'source' is a dummy variable, since we get the
605    # list of ISAs from env['ALL_ISA_LIST'].
606    def gen_switch_hdr(target, source, env):
607        fname = str(target[0])
608        basename = os.path.basename(fname)
609        f = open(fname, 'w')
610        f.write('#include "arch/isa_specific.hh"\n')
611        cond = '#if'
612        for isa in all_isa_list:
613            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
614                    % (cond, isa.upper(), dirname, isa, basename))
615            cond = '#elif'
616        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
617        f.close()
618        return 0
619
620    # String to print when generating header
621    def gen_switch_hdr_string(target, source, env):
622        return "Generating switch header " + str(target[0])
623
624    # Build SCons Action object. 'varlist' specifies env vars that this
625    # action depends on; when env['ALL_ISA_LIST'] changes these actions
626    # should get re-executed.
627    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
628                               varlist=['ALL_ISA_LIST'])
629
630    # Instantiate actions for each header
631    for hdr in switch_headers:
632        env.Command(hdr, [], switch_hdr_action)
633Export('make_switching_dir')
634
635###################################################
636#
637# Define build environments for selected configurations.
638#
639###################################################
640
641# rename base env
642base_env = env
643
644for build_path in build_paths:
645    print "Building in", build_path
646    env['BUILDDIR'] = build_path
647
648    # build_dir is the tail component of build path, and is used to
649    # determine the build parameters (e.g., 'ALPHA_SE')
650    (build_root, build_dir) = os.path.split(build_path)
651    # Make a copy of the build-root environment to use for this config.
652    env = base_env.Copy()
653
654    # Set env options according to the build directory config.
655    sticky_opts.files = []
656    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
657    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
658    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
659    current_opts_file = joinpath(build_root, 'options', build_dir)
660    if os.path.isfile(current_opts_file):
661        sticky_opts.files.append(current_opts_file)
662        print "Using saved options file %s" % current_opts_file
663    else:
664        # Build dir-specific options file doesn't exist.
665
666        # Make sure the directory is there so we can create it later
667        opt_dir = os.path.dirname(current_opts_file)
668        if not os.path.isdir(opt_dir):
669            os.mkdir(opt_dir)
670
671        # Get default build options from source tree.  Options are
672        # normally determined by name of $BUILD_DIR, but can be
673        # overriden by 'default=' arg on command line.
674        default_opts_file = joinpath('build_opts',
675                                     ARGUMENTS.get('default', build_dir))
676        if os.path.isfile(default_opts_file):
677            sticky_opts.files.append(default_opts_file)
678            print "Options file %s not found,\n  using defaults in %s" \
679                  % (current_opts_file, default_opts_file)
680        else:
681            print "Error: cannot find options file %s or %s" \
682                  % (current_opts_file, default_opts_file)
683            Exit(1)
684
685    # Apply current option settings to env
686    sticky_opts.Update(env)
687    nonsticky_opts.Update(env)
688
689    help_text += "Sticky options for %s:\n" % build_dir \
690                 + sticky_opts.GenerateHelpText(env) \
691                 + "\nNon-sticky options for %s:\n" % build_dir \
692                 + nonsticky_opts.GenerateHelpText(env)
693
694    # Process option settings.
695
696    if not have_fenv and env['USE_FENV']:
697        print "Warning: <fenv.h> not available; " \
698              "forcing USE_FENV to False in", build_dir + "."
699        env['USE_FENV'] = False
700
701    if not env['USE_FENV']:
702        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
703        print "         FP results may deviate slightly from other platforms."
704
705    if env['EFENCE']:
706        env.Append(LIBS=['efence'])
707
708    if env['USE_MYSQL']:
709        if not have_mysql:
710            print "Warning: MySQL not available; " \
711                  "forcing USE_MYSQL to False in", build_dir + "."
712            env['USE_MYSQL'] = False
713        else:
714            print "Compiling in", build_dir, "with MySQL support."
715            env.ParseConfig(mysql_config_libs)
716            env.ParseConfig(mysql_config_include)
717
718    # Save sticky option settings back to current options file
719    sticky_opts.Save(current_opts_file, env)
720
721    # Do this after we save setting back, or else we'll tack on an
722    # extra 'qdo' every time we run scons.
723    if env['BATCH']:
724        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
725        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
726
727    if env['USE_SSE2']:
728        env.Append(CCFLAGS='-msse2')
729
730    # The src/SConscript file sets up the build rules in 'env' according
731    # to the configured options.  It returns a list of environments,
732    # one for each variant build (debug, opt, etc.)
733    envList = SConscript('src/SConscript', build_dir = build_path,
734                         exports = 'env')
735
736    # Set up the regression tests for each build.
737    for e in envList:
738        SConscript('tests/SConscript',
739                   build_dir = joinpath(build_path, 'tests', e.Label),
740                   exports = { 'env' : e }, duplicate = False)
741
742Help(help_text)
743
744
745###################################################
746#
747# Let SCons do its thing.  At this point SCons will use the defined
748# build environments to build the requested targets.
749#
750###################################################
751
752