SConstruct revision 5708:96614cd66f76
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 re
69
70from os.path import isdir, isfile, join as joinpath
71
72import SCons
73
74# Check for recent-enough Python and SCons versions.  If your system's
75# default installation of Python is not recent enough, you can use a
76# non-default installation of the Python interpreter by either (1)
77# rearranging your PATH so that scons finds the non-default 'python'
78# first or (2) explicitly invoking an alternative interpreter on the
79# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
80EnsurePythonVersion(2,4)
81
82# Import subprocess after we check the version since it doesn't exist in
83# Python < 2.4.
84import subprocess
85
86# helper function: compare arrays or strings of version numbers.
87# E.g., compare_version((1,3,25), (1,4,1)')
88# returns -1, 0, 1 if v1 is <, ==, > v2
89def compare_versions(v1, v2):
90    def make_version_list(v):
91        if isinstance(v, (list,tuple)):
92            return v
93        elif isinstance(v, str):
94            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
95        else:
96            raise TypeError
97
98    v1 = make_version_list(v1)
99    v2 = make_version_list(v2)
100    # Compare corresponding elements of lists
101    for n1,n2 in zip(v1, v2):
102        if n1 < n2: return -1
103        if n1 > n2: return  1
104    # all corresponding values are equal... see if one has extra values
105    if len(v1) < len(v2): return -1
106    if len(v1) > len(v2): return  1
107    return 0
108
109# SCons version numbers need special processing because they can have
110# charecters and an release date embedded in them. This function does
111# the magic to extract them in a similar way to the SCons internal function
112# function does and then checks that the current version is not contained in
113# a list of version tuples (bad_ver_strs)
114def CheckSCons(bad_ver_strs):
115    def scons_ver(v):
116        num_parts = v.split(' ')[0].split('.')
117        major = int(num_parts[0])
118        minor = int(re.match('\d+', num_parts[1]).group())
119        rev = 0
120        rdate = 0
121        if len(num_parts) > 2:
122            try: rev = int(re.match('\d+', num_parts[2]).group())
123            except: pass
124            rev_parts = num_parts[2].split('d')
125            if len(rev_parts) > 1:
126                rdate = int(re.match('\d+', rev_parts[1]).group())
127
128        return (major, minor, rev, rdate)
129
130    sc_ver = scons_ver(SCons.__version__)
131    for bad_ver in bad_ver_strs:
132        bv = (scons_ver(bad_ver[0]), scons_ver(bad_ver[1]))
133        if  compare_versions(sc_ver, bv[0]) != -1 and\
134            compare_versions(sc_ver, bv[1]) != 1:
135            print "The version of SCons that you have installed: ", SCons.__version__
136            print "has a bug that prevents it from working correctly with M5."
137            print "Please install a version NOT contained within the following",
138            print "ranges (inclusive):"
139            for bad_ver in bad_ver_strs:
140                print "    %s - %s" % bad_ver
141            Exit(2)
142
143CheckSCons(( 
144    # We need a version that is 0.96.91 or newer
145    ('0.0.0', '0.96.90'), 
146    ))
147
148
149# The absolute path to the current directory (where this file lives).
150ROOT = Dir('.').abspath
151
152# Path to the M5 source tree.
153SRCDIR = joinpath(ROOT, 'src')
154
155# tell python where to find m5 python code
156sys.path.append(joinpath(ROOT, 'src/python'))
157
158def check_style_hook(ui):
159    ui.readconfig(joinpath(ROOT, '.hg', 'hgrc'))
160    style_hook = ui.config('hooks', 'pretxncommit.style', None)
161
162    if not style_hook:
163        print """\
164You're missing the M5 style hook.
165Please install the hook so we can ensure that all code fits a common style.
166
167All you'd need to do is add the following lines to your repository .hg/hgrc
168or your personal .hgrc
169----------------
170
171[extensions]
172style = %s/util/style.py
173
174[hooks]
175pretxncommit.style = python:style.check_whitespace
176""" % (ROOT)
177        sys.exit(1)
178
179if ARGUMENTS.get('IGNORE_STYLE') != 'True' and isdir(joinpath(ROOT, '.hg')):
180    try:
181        from mercurial import ui
182        check_style_hook(ui.ui())
183    except ImportError:
184        pass
185
186###################################################
187#
188# Figure out which configurations to set up based on the path(s) of
189# the target(s).
190#
191###################################################
192
193# Find default configuration & binary.
194Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
195
196# helper function: find last occurrence of element in list
197def rfind(l, elt, offs = -1):
198    for i in range(len(l)+offs, 0, -1):
199        if l[i] == elt:
200            return i
201    raise ValueError, "element not found"
202
203# Each target must have 'build' in the interior of the path; the
204# directory below this will determine the build parameters.  For
205# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
206# recognize that ALPHA_SE specifies the configuration because it
207# follow 'build' in the bulid path.
208
209# Generate absolute paths to targets so we can see where the build dir is
210if COMMAND_LINE_TARGETS:
211    # Ask SCons which directory it was invoked from
212    launch_dir = GetLaunchDir()
213    # Make targets relative to invocation directory
214    abs_targets = map(lambda x: os.path.normpath(joinpath(launch_dir, str(x))),
215                      COMMAND_LINE_TARGETS)
216else:
217    # Default targets are relative to root of tree
218    abs_targets = map(lambda x: os.path.normpath(joinpath(ROOT, str(x))),
219                      DEFAULT_TARGETS)
220
221
222# Generate a list of the unique build roots and configs that the
223# collected targets reference.
224build_paths = []
225build_root = None
226for t in abs_targets:
227    path_dirs = t.split('/')
228    try:
229        build_top = rfind(path_dirs, 'build', -2)
230    except:
231        print "Error: no non-leaf 'build' dir found on target path", t
232        Exit(1)
233    this_build_root = joinpath('/',*path_dirs[:build_top+1])
234    if not build_root:
235        build_root = this_build_root
236    else:
237        if this_build_root != build_root:
238            print "Error: build targets not under same build root\n"\
239                  "  %s\n  %s" % (build_root, this_build_root)
240            Exit(1)
241    build_path = joinpath('/',*path_dirs[:build_top+2])
242    if build_path not in build_paths:
243        build_paths.append(build_path)
244
245# Make sure build_root exists (might not if this is the first build there)
246if not isdir(build_root):
247    os.mkdir(build_root)
248
249###################################################
250#
251# Set up the default build environment.  This environment is copied
252# and modified according to each selected configuration.
253#
254###################################################
255
256env = Environment(ENV = os.environ,  # inherit user's environment vars
257                  ROOT = ROOT,
258                  SRCDIR = SRCDIR)
259
260Export('env')
261
262env.SConsignFile(joinpath(build_root,"sconsign"))
263
264# Default duplicate option is to use hard links, but this messes up
265# when you use emacs to edit a file in the target dir, as emacs moves
266# file to file~ then copies to file, breaking the link.  Symbolic
267# (soft) links work better.
268env.SetOption('duplicate', 'soft-copy')
269
270# I waffle on this setting... it does avoid a few painful but
271# unnecessary builds, but it also seems to make trivial builds take
272# noticeably longer.
273if False:
274    env.TargetSignatures('content')
275
276#
277# Set up global sticky options... these are common to an entire build
278# tree (not specific to a particular build like ALPHA_SE)
279#
280
281# Option validators & converters for global sticky options
282def PathListMakeAbsolute(val):
283    if not val:
284        return val
285    f = lambda p: os.path.abspath(os.path.expanduser(p))
286    return ':'.join(map(f, val.split(':')))
287
288def PathListAllExist(key, val, env):
289    if not val:
290        return
291    paths = val.split(':')
292    for path in paths:
293        if not isdir(path):
294            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
295
296global_sticky_opts_file = joinpath(build_root, 'options.global')
297
298global_sticky_opts = Options(global_sticky_opts_file, args=ARGUMENTS)
299
300global_sticky_opts.AddOptions(
301    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
302    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
303    ('BATCH', 'Use batch pool for build and tests', False),
304    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
305    ('EXTRAS', 'Add Extra directories to the compilation', '',
306     PathListAllExist, PathListMakeAbsolute)
307    )    
308
309
310# base help text
311help_text = '''
312Usage: scons [scons options] [build options] [target(s)]
313
314'''
315
316help_text += "Global sticky options:\n" \
317             + global_sticky_opts.GenerateHelpText(env)
318
319# Update env with values from ARGUMENTS & file global_sticky_opts_file
320global_sticky_opts.Update(env)
321
322# Save sticky option settings back to current options file
323global_sticky_opts.Save(global_sticky_opts_file, env)
324
325# Parse EXTRAS option to build list of all directories where we're
326# look for sources etc.  This list is exported as base_dir_list.
327base_dir_list = [joinpath(ROOT, 'src')]
328if env['EXTRAS']:
329    base_dir_list += env['EXTRAS'].split(':')
330
331Export('base_dir_list')
332
333# M5_PLY is used by isa_parser.py to find the PLY package.
334env.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
335env['GCC'] = subprocess.Popen(env['CXX'] + ' --version', shell=True,
336        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
337        close_fds=True).communicate()[0].find('g++') >= 0
338env['SUNCC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
339        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
340        close_fds=True).communicate()[0].find('Sun C++') >= 0
341env['ICC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
342        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
343        close_fds=True).communicate()[0].find('Intel') >= 0
344if env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
345    print 'Error: How can we have two at the same time?'
346    Exit(1)
347
348
349# Set up default C++ compiler flags
350if env['GCC']:
351    env.Append(CCFLAGS='-pipe')
352    env.Append(CCFLAGS='-fno-strict-aliasing')
353    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
354    env.Append(CXXFLAGS='-Wno-deprecated')
355elif env['ICC']:
356    pass #Fix me... add warning flags once we clean up icc warnings
357elif env['SUNCC']:
358    env.Append(CCFLAGS='-Qoption ccfe')
359    env.Append(CCFLAGS='-features=gcc')
360    env.Append(CCFLAGS='-features=extensions')
361    env.Append(CCFLAGS='-library=stlport4')
362    env.Append(CCFLAGS='-xar')
363#    env.Append(CCFLAGS='-instances=semiexplicit')
364else:
365    print 'Error: Don\'t know what compiler options to use for your compiler.'
366    print '       Please fix SConstruct and src/SConscript and try again.'
367    Exit(1)
368
369# Do this after we save setting back, or else we'll tack on an
370# extra 'qdo' every time we run scons.
371if env['BATCH']:
372    env['CC']     = env['BATCH_CMD'] + ' ' + env['CC']
373    env['CXX']    = env['BATCH_CMD'] + ' ' + env['CXX']
374    env['AS']     = env['BATCH_CMD'] + ' ' + env['AS']
375    env['AR']     = env['BATCH_CMD'] + ' ' + env['AR']
376    env['RANLIB'] = env['BATCH_CMD'] + ' ' + env['RANLIB']
377
378if sys.platform == 'cygwin':
379    # cygwin has some header file issues...
380    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
381env.Append(CPPPATH=[Dir('ext/dnet')])
382
383# Check for SWIG
384if not env.has_key('SWIG'):
385    print 'Error: SWIG utility not found.'
386    print '       Please install (see http://www.swig.org) and retry.'
387    Exit(1)
388
389# Check for appropriate SWIG version
390swig_version = os.popen('swig -version').read().split()
391# First 3 words should be "SWIG Version x.y.z"
392if len(swig_version) < 3 or \
393        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
394    print 'Error determining SWIG version.'
395    Exit(1)
396
397min_swig_version = '1.3.28'
398if compare_versions(swig_version[2], min_swig_version) < 0:
399    print 'Error: SWIG version', min_swig_version, 'or newer required.'
400    print '       Installed version:', swig_version[2]
401    Exit(1)
402
403# Set up SWIG flags & scanner
404swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
405env.Append(SWIGFLAGS=swig_flags)
406
407# filter out all existing swig scanners, they mess up the dependency
408# stuff for some reason
409scanners = []
410for scanner in env['SCANNERS']:
411    skeys = scanner.skeys
412    if skeys == '.i':
413        continue
414
415    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
416        continue
417
418    scanners.append(scanner)
419
420# add the new swig scanner that we like better
421from SCons.Scanner import ClassicCPP as CPPScanner
422swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
423scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
424
425# replace the scanners list that has what we want
426env['SCANNERS'] = scanners
427
428# Add a custom Check function to the Configure context so that we can
429# figure out if the compiler adds leading underscores to global
430# variables.  This is needed for the autogenerated asm files that we
431# use for embedding the python code.
432def CheckLeading(context):
433    context.Message("Checking for leading underscore in global variables...")
434    # 1) Define a global variable called x from asm so the C compiler
435    #    won't change the symbol at all.
436    # 2) Declare that variable.
437    # 3) Use the variable
438    #
439    # If the compiler prepends an underscore, this will successfully
440    # link because the external symbol 'x' will be called '_x' which
441    # was defined by the asm statement.  If the compiler does not
442    # prepend an underscore, this will not successfully link because
443    # '_x' will have been defined by assembly, while the C portion of
444    # the code will be trying to use 'x'
445    ret = context.TryLink('''
446        asm(".globl _x; _x: .byte 0");
447        extern int x;
448        int main() { return x; }
449        ''', extension=".c")
450    context.env.Append(LEADING_UNDERSCORE=ret)
451    context.Result(ret)
452    return ret
453
454# Platform-specific configuration.  Note again that we assume that all
455# builds under a given build root run on the same host platform.
456conf = Configure(env,
457                 conf_dir = joinpath(build_root, '.scons_config'),
458                 log_file = joinpath(build_root, 'scons_config.log'),
459                 custom_tests = { 'CheckLeading' : CheckLeading })
460
461# Check for leading underscores.  Don't really need to worry either
462# way so don't need to check the return code.
463conf.CheckLeading()
464
465# Check if we should compile a 64 bit binary on Mac OS X/Darwin
466try:
467    import platform
468    uname = platform.uname()
469    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
470        if int(subprocess.Popen('sysctl -n hw.cpu64bit_capable', shell=True,
471               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
472               close_fds=True).communicate()[0][0]):
473            env.Append(CCFLAGS='-arch x86_64')
474            env.Append(CFLAGS='-arch x86_64')
475            env.Append(LINKFLAGS='-arch x86_64')
476            env.Append(ASFLAGS='-arch x86_64')
477except:
478    pass
479
480# Recent versions of scons substitute a "Null" object for Configure()
481# when configuration isn't necessary, e.g., if the "--help" option is
482# present.  Unfortuantely this Null object always returns false,
483# breaking all our configuration checks.  We replace it with our own
484# more optimistic null object that returns True instead.
485if not conf:
486    def NullCheck(*args, **kwargs):
487        return True
488
489    class NullConf:
490        def __init__(self, env):
491            self.env = env
492        def Finish(self):
493            return self.env
494        def __getattr__(self, mname):
495            return NullCheck
496
497    conf = NullConf(env)
498
499# Find Python include and library directories for embedding the
500# interpreter.  For consistency, we will use the same Python
501# installation used to run scons (and thus this script).  If you want
502# to link in an alternate version, see above for instructions on how
503# to invoke scons with a different copy of the Python interpreter.
504
505# Get brief Python version name (e.g., "python2.4") for locating
506# include & library files
507py_version_name = 'python' + sys.version[:3]
508
509# include path, e.g. /usr/local/include/python2.4
510py_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
511env.Append(CPPPATH = py_header_path)
512# verify that it works
513if not conf.CheckHeader('Python.h', '<>'):
514    print "Error: can't find Python.h header in", py_header_path
515    Exit(1)
516
517# add library path too if it's not in the default place
518py_lib_path = None
519if sys.exec_prefix != '/usr':
520    py_lib_path = joinpath(sys.exec_prefix, 'lib')
521elif sys.platform == 'cygwin':
522    # cygwin puts the .dll in /bin for some reason
523    py_lib_path = '/bin'
524if py_lib_path:
525    env.Append(LIBPATH = py_lib_path)
526    print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
527if not conf.CheckLib(py_version_name):
528    print "Error: can't find Python library", py_version_name
529    Exit(1)
530
531# On Solaris you need to use libsocket for socket ops
532if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
533   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
534       print "Can't find library with socket calls (e.g. accept())"
535       Exit(1)
536
537# Check for zlib.  If the check passes, libz will be automatically
538# added to the LIBS environment variable.
539if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
540    print 'Error: did not find needed zlib compression library '\
541          'and/or zlib.h header file.'
542    print '       Please install zlib and try again.'
543    Exit(1)
544
545# Check for <fenv.h> (C99 FP environment control)
546have_fenv = conf.CheckHeader('fenv.h', '<>')
547if not have_fenv:
548    print "Warning: Header file <fenv.h> not found."
549    print "         This host has no IEEE FP rounding mode control."
550
551# Check for mysql.
552mysql_config = WhereIs('mysql_config')
553have_mysql = mysql_config != None
554
555# Check MySQL version.
556if have_mysql:
557    mysql_version = os.popen(mysql_config + ' --version').read()
558    min_mysql_version = '4.1'
559    if compare_versions(mysql_version, min_mysql_version) < 0:
560        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
561        print '         Version', mysql_version, 'detected.'
562        have_mysql = False
563
564# Set up mysql_config commands.
565if have_mysql:
566    mysql_config_include = mysql_config + ' --include'
567    if os.system(mysql_config_include + ' > /dev/null') != 0:
568        # older mysql_config versions don't support --include, use
569        # --cflags instead
570        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
571    # This seems to work in all versions
572    mysql_config_libs = mysql_config + ' --libs'
573
574env = conf.Finish()
575
576# Define the universe of supported ISAs
577all_isa_list = [ ]
578Export('all_isa_list')
579
580# Define the universe of supported CPU models
581all_cpu_list = [ ]
582default_cpus = [ ]
583Export('all_cpu_list', 'default_cpus')
584
585# Sticky options get saved in the options file so they persist from
586# one invocation to the next (unless overridden, in which case the new
587# value becomes sticky).
588sticky_opts = Options(args=ARGUMENTS)
589Export('sticky_opts')
590
591# Non-sticky options only apply to the current build.
592nonsticky_opts = Options(args=ARGUMENTS)
593Export('nonsticky_opts')
594
595# Walk the tree and execute all SConsopts scripts that wil add to the
596# above options
597for base_dir in base_dir_list:
598    for root, dirs, files in os.walk(base_dir):
599        if 'SConsopts' in files:
600            print "Reading", joinpath(root, 'SConsopts')
601            SConscript(joinpath(root, 'SConsopts'))
602
603all_isa_list.sort()
604all_cpu_list.sort()
605default_cpus.sort()
606
607sticky_opts.AddOptions(
608    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
609    BoolOption('FULL_SYSTEM', 'Full-system support', False),
610    # There's a bug in scons 0.96.1 that causes ListOptions with list
611    # values (more than one value) not to be able to be restored from
612    # a saved option file.  If this causes trouble then upgrade to
613    # scons 0.96.90 or later.
614    ListOption('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
615    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
616    BoolOption('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
617               False),
618    BoolOption('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
619               False),
620    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
621               False),
622    BoolOption('SS_COMPATIBLE_FP',
623               'Make floating-point results compatible with SimpleScalar',
624               False),
625    BoolOption('USE_SSE2',
626               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
627               False),
628    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
629    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
630    BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
631    )
632
633nonsticky_opts.AddOptions(
634    BoolOption('update_ref', 'Update test reference outputs', False)
635    )
636
637# These options get exported to #defines in config/*.hh (see src/SConscript).
638env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
639                     'USE_MYSQL', 'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', \
640                     'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', \
641                     'USE_CHECKER', 'TARGET_ISA']
642
643# Define a handy 'no-op' action
644def no_action(target, source, env):
645    return 0
646
647env.NoAction = Action(no_action, None)
648
649###################################################
650#
651# Define a SCons builder for configuration flag headers.
652#
653###################################################
654
655# This function generates a config header file that #defines the
656# option symbol to the current option setting (0 or 1).  The source
657# operands are the name of the option and a Value node containing the
658# value of the option.
659def build_config_file(target, source, env):
660    (option, value) = [s.get_contents() for s in source]
661    f = file(str(target[0]), 'w')
662    print >> f, '#define', option, value
663    f.close()
664    return None
665
666# Generate the message to be printed when building the config file.
667def build_config_file_string(target, source, env):
668    (option, value) = [s.get_contents() for s in source]
669    return "Defining %s as %s in %s." % (option, value, target[0])
670
671# Combine the two functions into a scons Action object.
672config_action = Action(build_config_file, build_config_file_string)
673
674# The emitter munges the source & target node lists to reflect what
675# we're really doing.
676def config_emitter(target, source, env):
677    # extract option name from Builder arg
678    option = str(target[0])
679    # True target is config header file
680    target = joinpath('config', option.lower() + '.hh')
681    val = env[option]
682    if isinstance(val, bool):
683        # Force value to 0/1
684        val = int(val)
685    elif isinstance(val, str):
686        val = '"' + val + '"'
687
688    # Sources are option name & value (packaged in SCons Value nodes)
689    return ([target], [Value(option), Value(val)])
690
691config_builder = Builder(emitter = config_emitter, action = config_action)
692
693env.Append(BUILDERS = { 'ConfigFile' : config_builder })
694
695###################################################
696#
697# Define a SCons builder for copying files.  This is used by the
698# Python zipfile code in src/python/SConscript, but is placed up here
699# since it's potentially more generally applicable.
700#
701###################################################
702
703copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
704
705env.Append(BUILDERS = { 'CopyFile' : copy_builder })
706
707###################################################
708#
709# Define a simple SCons builder to concatenate files.
710#
711# Used to append the Python zip archive to the executable.
712#
713###################################################
714
715concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
716                                          'chmod +x $TARGET']))
717
718env.Append(BUILDERS = { 'Concat' : concat_builder })
719
720
721# libelf build is shared across all configs in the build root.
722env.SConscript('ext/libelf/SConscript',
723               build_dir = joinpath(build_root, 'libelf'),
724               exports = 'env')
725
726###################################################
727#
728# This function is used to set up a directory with switching headers
729#
730###################################################
731
732env['ALL_ISA_LIST'] = all_isa_list
733def make_switching_dir(dirname, switch_headers, env):
734    # Generate the header.  target[0] is the full path of the output
735    # header to generate.  'source' is a dummy variable, since we get the
736    # list of ISAs from env['ALL_ISA_LIST'].
737    def gen_switch_hdr(target, source, env):
738        fname = str(target[0])
739        basename = os.path.basename(fname)
740        f = open(fname, 'w')
741        f.write('#include "arch/isa_specific.hh"\n')
742        cond = '#if'
743        for isa in all_isa_list:
744            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
745                    % (cond, isa.upper(), dirname, isa, basename))
746            cond = '#elif'
747        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
748        f.close()
749        return 0
750
751    # String to print when generating header
752    def gen_switch_hdr_string(target, source, env):
753        return "Generating switch header " + str(target[0])
754
755    # Build SCons Action object. 'varlist' specifies env vars that this
756    # action depends on; when env['ALL_ISA_LIST'] changes these actions
757    # should get re-executed.
758    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
759                               varlist=['ALL_ISA_LIST'])
760
761    # Instantiate actions for each header
762    for hdr in switch_headers:
763        env.Command(hdr, [], switch_hdr_action)
764Export('make_switching_dir')
765
766###################################################
767#
768# Define build environments for selected configurations.
769#
770###################################################
771
772# rename base env
773base_env = env
774
775for build_path in build_paths:
776    print "Building in", build_path
777
778    # Make a copy of the build-root environment to use for this config.
779    env = base_env.Copy()
780    env['BUILDDIR'] = build_path
781
782    # build_dir is the tail component of build path, and is used to
783    # determine the build parameters (e.g., 'ALPHA_SE')
784    (build_root, build_dir) = os.path.split(build_path)
785
786    # Set env options according to the build directory config.
787    sticky_opts.files = []
788    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
789    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
790    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
791    current_opts_file = joinpath(build_root, 'options', build_dir)
792    if isfile(current_opts_file):
793        sticky_opts.files.append(current_opts_file)
794        print "Using saved options file %s" % current_opts_file
795    else:
796        # Build dir-specific options file doesn't exist.
797
798        # Make sure the directory is there so we can create it later
799        opt_dir = os.path.dirname(current_opts_file)
800        if not isdir(opt_dir):
801            os.mkdir(opt_dir)
802
803        # Get default build options from source tree.  Options are
804        # normally determined by name of $BUILD_DIR, but can be
805        # overriden by 'default=' arg on command line.
806        default_opts_file = joinpath('build_opts',
807                                     ARGUMENTS.get('default', build_dir))
808        if isfile(default_opts_file):
809            sticky_opts.files.append(default_opts_file)
810            print "Options file %s not found,\n  using defaults in %s" \
811                  % (current_opts_file, default_opts_file)
812        else:
813            print "Error: cannot find options file %s or %s" \
814                  % (current_opts_file, default_opts_file)
815            Exit(1)
816
817    # Apply current option settings to env
818    sticky_opts.Update(env)
819    nonsticky_opts.Update(env)
820
821    help_text += "\nSticky options for %s:\n" % build_dir \
822                 + sticky_opts.GenerateHelpText(env) \
823                 + "\nNon-sticky options for %s:\n" % build_dir \
824                 + nonsticky_opts.GenerateHelpText(env)
825
826    # Process option settings.
827
828    if not have_fenv and env['USE_FENV']:
829        print "Warning: <fenv.h> not available; " \
830              "forcing USE_FENV to False in", build_dir + "."
831        env['USE_FENV'] = False
832
833    if not env['USE_FENV']:
834        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
835        print "         FP results may deviate slightly from other platforms."
836
837    if env['EFENCE']:
838        env.Append(LIBS=['efence'])
839
840    if env['USE_MYSQL']:
841        if not have_mysql:
842            print "Warning: MySQL not available; " \
843                  "forcing USE_MYSQL to False in", build_dir + "."
844            env['USE_MYSQL'] = False
845        else:
846            print "Compiling in", build_dir, "with MySQL support."
847            env.ParseConfig(mysql_config_libs)
848            env.ParseConfig(mysql_config_include)
849
850    # Save sticky option settings back to current options file
851    sticky_opts.Save(current_opts_file, env)
852
853    if env['USE_SSE2']:
854        env.Append(CCFLAGS='-msse2')
855
856    # The src/SConscript file sets up the build rules in 'env' according
857    # to the configured options.  It returns a list of environments,
858    # one for each variant build (debug, opt, etc.)
859    envList = SConscript('src/SConscript', build_dir = build_path,
860                         exports = 'env')
861
862    # Set up the regression tests for each build.
863    for e in envList:
864        SConscript('tests/SConscript',
865                   build_dir = joinpath(build_path, 'tests', e.Label),
866                   exports = { 'env' : e }, duplicate = False)
867
868Help(help_text)
869
870
871###################################################
872#
873# Let SCons do its thing.  At this point SCons will use the defined
874# build environments to build the requested targets.
875#
876###################################################
877
878