SConstruct revision 2632:1bb2f91485ea
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###################################################
30#
31# SCons top-level build description (SConstruct) file.
32#
33# While in this directory ('m5'), just type 'scons' to build the default
34# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
35# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
36# the optimized full-system version).
37#
38# You can build M5 in a different directory as long as there is a
39# 'build/<CONFIG>' somewhere along the target path.  The build system
40# expdects that all configs under the same build directory are being
41# built for the same host system.
42#
43# Examples:
44#   These two commands are equivalent.  The '-u' option tells scons to
45#   search up the directory tree for this SConstruct file.
46#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
47#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
48#   These two commands are equivalent and demonstrate building in a
49#   directory outside of the source tree.  The '-C' option tells scons
50#   to chdir to the specified directory to find this SConstruct file.
51#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
52#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
53#
54# You can use 'scons -H' to print scons options.  If you're in this
55# 'm5' directory (or use -u or -C to tell scons where to find this
56# file), you can use 'scons -h' to print all the M5-specific build
57# options as well.
58#
59###################################################
60
61# Python library imports
62import sys
63import os
64
65# Check for recent-enough Python and SCons versions
66EnsurePythonVersion(2,3)
67EnsureSConsVersion(0,96,91)
68
69# The absolute path to the current directory (where this file lives).
70ROOT = Dir('.').abspath
71
72# Paths to the M5 and external source trees.
73SRCDIR = os.path.join(ROOT, 'src')
74
75# tell python where to find m5 python code
76sys.path.append(os.path.join(ROOT, 'src/python'))
77
78###################################################
79#
80# Figure out which configurations to set up based on the path(s) of
81# the target(s).
82#
83###################################################
84
85# Find default configuration & binary.
86Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
87
88# Ask SCons which directory it was invoked from.
89launch_dir = GetLaunchDir()
90
91# Make targets relative to invocation directory
92abs_targets = map(lambda x: os.path.normpath(os.path.join(launch_dir, str(x))),
93                  BUILD_TARGETS)
94
95# helper function: find last occurrence of element in list
96def rfind(l, elt, offs = -1):
97    for i in range(len(l)+offs, 0, -1):
98        if l[i] == elt:
99            return i
100    raise ValueError, "element not found"
101
102# Each target must have 'build' in the interior of the path; the
103# directory below this will determine the build parameters.  For
104# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
105# recognize that ALPHA_SE specifies the configuration because it
106# follow 'build' in the bulid path.
107
108# Generate a list of the unique configs that the collected targets
109# reference.
110build_paths = []
111for t in abs_targets:
112    path_dirs = t.split('/')
113    try:
114        build_top = rfind(path_dirs, 'build', -2)
115    except:
116        print "Error: no non-leaf 'build' dir found on target path", t
117        Exit(1)
118    config_dir = os.path.join('/',*path_dirs[:build_top+2])
119    if config_dir not in build_paths:
120        build_paths.append(config_dir)
121
122###################################################
123#
124# Set up the default build environment.  This environment is copied
125# and modified according to each selected configuration.
126#
127###################################################
128
129env = Environment(ENV = os.environ,  # inherit user's environment vars
130                  ROOT = ROOT,
131                  SRCDIR = SRCDIR)
132
133env.SConsignFile("sconsign")
134
135# I waffle on this setting... it does avoid a few painful but
136# unnecessary builds, but it also seems to make trivial builds take
137# noticeably longer.
138if False:
139    env.TargetSignatures('content')
140
141# M5_PLY is used by isa_parser.py to find the PLY package.
142env.Append(ENV = { 'M5_PLY' : Dir('ext/ply') })
143
144# Set up default C++ compiler flags
145env.Append(CCFLAGS='-pipe')
146env.Append(CCFLAGS='-fno-strict-aliasing')
147env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
148if sys.platform == 'cygwin':
149    # cygwin has some header file issues...
150    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
151env.Append(CPPPATH=[Dir('ext/dnet')])
152
153# Default libraries
154env.Append(LIBS=['z'])
155
156# Platform-specific configuration
157conf = Configure(env)
158
159# Check for <fenv.h> (C99 FP environment control)
160have_fenv = conf.CheckHeader('fenv.h', '<>')
161if not have_fenv:
162    print "Warning: Header file <fenv.h> not found."
163    print "         This host has no IEEE FP rounding mode control."
164
165# Check for mysql.
166mysql_config = WhereIs('mysql_config')
167have_mysql = mysql_config != None
168
169# Check MySQL version.
170if have_mysql:
171    mysql_version = os.popen(mysql_config + ' --version').read()
172    mysql_version = mysql_version.split('.')
173    mysql_major = int(mysql_version[0])
174    mysql_minor = int(mysql_version[1])
175    # This version check is probably overly conservative, but it deals
176    # with the versions we have installed.
177    if mysql_major < 4 or (mysql_major == 4 and mysql_minor < 1):
178        print "Warning: MySQL v4.1 or newer required."
179        have_mysql = False
180
181# Set up mysql_config commands.
182if have_mysql:
183    mysql_config_include = mysql_config + ' --include'
184    if os.system(mysql_config_include + ' > /dev/null') != 0:
185        # older mysql_config versions don't support --include, use
186        # --cflags instead
187        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
188    # This seems to work in all versions
189    mysql_config_libs = mysql_config + ' --libs'
190
191env = conf.Finish()
192
193# Define the universe of supported ISAs
194env['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
195
196# Define the universe of supported CPU models
197env['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
198                       'FastCPU', 'FullCPU', 'AlphaFullCPU']
199
200# Sticky options get saved in the options file so they persist from
201# one invocation to the next (unless overridden, in which case the new
202# value becomes sticky).
203sticky_opts = Options(args=ARGUMENTS)
204sticky_opts.AddOptions(
205    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env['ALL_ISA_LIST']),
206    BoolOption('FULL_SYSTEM', 'Full-system support', False),
207    # There's a bug in scons 0.96.1 that causes ListOptions with list
208    # values (more than one value) not to be able to be restored from
209    # a saved option file.  If this causes trouble then upgrade to
210    # scons 0.96.90 or later.
211    ListOption('CPU_MODELS', 'CPU models', 'all', env['ALL_CPU_LIST']),
212    BoolOption('ALPHA_TLASER',
213               'Model Alpha TurboLaser platform (vs. Tsunami)', False),
214    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
215    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
216               False),
217    BoolOption('SS_COMPATIBLE_FP',
218               'Make floating-point results compatible with SimpleScalar',
219               False),
220    BoolOption('USE_SSE2',
221               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
222               False),
223    BoolOption('STATS_BINNING', 'Bin statistics by CPU mode', have_mysql),
224    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
225    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
226    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
227    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
228    BoolOption('BATCH', 'Use batch pool for build and tests', False),
229    ('BATCH_CMD', 'Batch pool submission command name', 'qdo')
230    )
231
232# Non-sticky options only apply to the current build.
233nonsticky_opts = Options(args=ARGUMENTS)
234nonsticky_opts.AddOptions(
235    BoolOption('update_ref', 'Update test reference outputs', False)
236    )
237
238# These options get exported to #defines in config/*.hh (see m5/SConscript).
239env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
240                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
241                     'STATS_BINNING']
242
243# Define a handy 'no-op' action
244def no_action(target, source, env):
245    return 0
246
247env.NoAction = Action(no_action, None)
248
249# libelf build is described in its own SConscript file.
250# SConscript-global is the build in build/libelf shared among all
251# configs.
252env.SConscript('src/libelf/SConscript-global', exports = 'env')
253
254###################################################
255#
256# Define a SCons builder for configuration flag headers.
257#
258###################################################
259
260# This function generates a config header file that #defines the
261# option symbol to the current option setting (0 or 1).  The source
262# operands are the name of the option and a Value node containing the
263# value of the option.
264def build_config_file(target, source, env):
265    (option, value) = [s.get_contents() for s in source]
266    f = file(str(target[0]), 'w')
267    print >> f, '#define', option, value
268    f.close()
269    return None
270
271# Generate the message to be printed when building the config file.
272def build_config_file_string(target, source, env):
273    (option, value) = [s.get_contents() for s in source]
274    return "Defining %s as %s in %s." % (option, value, target[0])
275
276# Combine the two functions into a scons Action object.
277config_action = Action(build_config_file, build_config_file_string)
278
279# The emitter munges the source & target node lists to reflect what
280# we're really doing.
281def config_emitter(target, source, env):
282    # extract option name from Builder arg
283    option = str(target[0])
284    # True target is config header file
285    target = os.path.join('config', option.lower() + '.hh')
286    # Force value to 0/1 even if it's a Python bool
287    val = int(eval(str(env[option])))
288    # Sources are option name & value (packaged in SCons Value nodes)
289    return ([target], [Value(option), Value(val)])
290
291config_builder = Builder(emitter = config_emitter, action = config_action)
292
293env.Append(BUILDERS = { 'ConfigFile' : config_builder })
294
295###################################################
296#
297# Define build environments for selected configurations.
298#
299###################################################
300
301# rename base env
302base_env = env
303
304help_text = '''
305Usage: scons [scons options] [build options] [target(s)]
306
307'''
308
309for build_path in build_paths:
310    print "Building in", build_path
311    # build_dir is the tail component of build path, and is used to
312    # determine the build parameters (e.g., 'ALPHA_SE')
313    (build_root, build_dir) = os.path.split(build_path)
314    # Make a copy of the default environment to use for this config.
315    env = base_env.Copy()
316
317    # Set env options according to the build directory config.
318    sticky_opts.files = []
319    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
320    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
321    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
322    current_opts_file = os.path.join(build_root, 'options', build_dir)
323    if os.path.isfile(current_opts_file):
324        sticky_opts.files.append(current_opts_file)
325        print "Using saved options file %s" % current_opts_file
326    else:
327        # Build dir-specific options file doesn't exist.
328
329        # Make sure the directory is there so we can create it later
330        opt_dir = os.path.dirname(current_opts_file)
331        if not os.path.isdir(opt_dir):
332            os.mkdir(opt_dir)
333
334        # Get default build options from source tree.  Options are
335        # normally determined by name of $BUILD_DIR, but can be
336        # overriden by 'default=' arg on command line.
337        default_opts_file = os.path.join('build_opts',
338                                         ARGUMENTS.get('default', build_dir))
339        if os.path.isfile(default_opts_file):
340            sticky_opts.files.append(default_opts_file)
341            print "Options file %s not found,\n  using defaults in %s" \
342                  % (current_opts_file, default_opts_file)
343        else:
344            print "Error: cannot find options file %s or %s" \
345                  % (current_opts_file, default_opts_file)
346            Exit(1)
347
348    # Apply current option settings to env
349    sticky_opts.Update(env)
350    nonsticky_opts.Update(env)
351
352    help_text += "Sticky options for %s:\n" % build_dir \
353                 + sticky_opts.GenerateHelpText(env) \
354                 + "\nNon-sticky options for %s:\n" % build_dir \
355                 + nonsticky_opts.GenerateHelpText(env)
356
357    # Process option settings.
358
359    if not have_fenv and env['USE_FENV']:
360        print "Warning: <fenv.h> not available; " \
361              "forcing USE_FENV to False in", build_dir + "."
362        env['USE_FENV'] = False
363
364    if not env['USE_FENV']:
365        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
366        print "         FP results may deviate slightly from other platforms."
367
368    if env['EFENCE']:
369        env.Append(LIBS=['efence'])
370
371    if env['USE_MYSQL']:
372        if not have_mysql:
373            print "Warning: MySQL not available; " \
374                  "forcing USE_MYSQL to False in", build_dir + "."
375            env['USE_MYSQL'] = False
376        else:
377            print "Compiling in", build_dir, "with MySQL support."
378            env.ParseConfig(mysql_config_libs)
379            env.ParseConfig(mysql_config_include)
380
381    # Save sticky option settings back to current options file
382    sticky_opts.Save(current_opts_file, env)
383
384    # Do this after we save setting back, or else we'll tack on an
385    # extra 'qdo' every time we run scons.
386    if env['BATCH']:
387        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
388        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
389
390    if env['USE_SSE2']:
391        env.Append(CCFLAGS='-msse2')
392
393    # The m5/SConscript file sets up the build rules in 'env' according
394    # to the configured options.  It returns a list of environments,
395    # one for each variant build (debug, opt, etc.)
396    envList = SConscript('src/SConscript', build_dir = build_path,
397                         exports = 'env', duplicate = False)
398
399    # Set up the regression tests for each build.
400#    for e in envList:
401#        SConscript('m5-test/SConscript',
402#                   build_dir = os.path.join(build_dir, 'test', e.Label),
403#                   exports = { 'env' : e }, duplicate = False)
404
405Help(help_text)
406
407###################################################
408#
409# Let SCons do its thing.  At this point SCons will use the defined
410# build environments to build the requested targets.
411#
412###################################################
413
414