SConstruct revision 2653:c27948389a6e
111723Sar4jc@virginia.edu# -*- mode:python -*-
211723Sar4jc@virginia.edu
311723Sar4jc@virginia.edu# Copyright (c) 2004-2005 The Regents of The University of Michigan
411723Sar4jc@virginia.edu# All rights reserved.
511723Sar4jc@virginia.edu#
611723Sar4jc@virginia.edu# Redistribution and use in source and binary forms, with or without
711723Sar4jc@virginia.edu# modification, are permitted provided that the following conditions are
811723Sar4jc@virginia.edu# met: redistributions of source code must retain the above copyright
911723Sar4jc@virginia.edu# notice, this list of conditions and the following disclaimer;
1011723Sar4jc@virginia.edu# redistributions in binary form must reproduce the above copyright
1111723Sar4jc@virginia.edu# notice, this list of conditions and the following disclaimer in the
1211723Sar4jc@virginia.edu# documentation and/or other materials provided with the distribution;
1311723Sar4jc@virginia.edu# neither the name of the copyright holders nor the names of its
1411723Sar4jc@virginia.edu# contributors may be used to endorse or promote products derived from
1511723Sar4jc@virginia.edu# this software without specific prior written permission.
1611723Sar4jc@virginia.edu#
1711723Sar4jc@virginia.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1811723Sar4jc@virginia.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1911723Sar4jc@virginia.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2011723Sar4jc@virginia.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2111723Sar4jc@virginia.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2211723Sar4jc@virginia.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2311723Sar4jc@virginia.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2411723Sar4jc@virginia.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2511723Sar4jc@virginia.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2611723Sar4jc@virginia.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2711723Sar4jc@virginia.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2811723Sar4jc@virginia.edu
2911723Sar4jc@virginia.edu###################################################
3011723Sar4jc@virginia.edu#
3111723Sar4jc@virginia.edu# SCons top-level build description (SConstruct) file.
3212808Srobert.scheffel1@tu-dresden.de#
3311723Sar4jc@virginia.edu# While in this directory ('m5'), just type 'scons' to build the default
3411723Sar4jc@virginia.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
3511723Sar4jc@virginia.edu# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
3611723Sar4jc@virginia.edu# the optimized full-system version).
3711723Sar4jc@virginia.edu#
3811723Sar4jc@virginia.edu# You can build M5 in a different directory as long as there is a
3911723Sar4jc@virginia.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
4011723Sar4jc@virginia.edu# expdects that all configs under the same build directory are being
4111723Sar4jc@virginia.edu# built for the same host system.
4211723Sar4jc@virginia.edu#
4311723Sar4jc@virginia.edu# Examples:
4411723Sar4jc@virginia.edu#   These two commands are equivalent.  The '-u' option tells scons to
4511723Sar4jc@virginia.edu#   search up the directory tree for this SConstruct file.
4611723Sar4jc@virginia.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
4711723Sar4jc@virginia.edu#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
4811723Sar4jc@virginia.edu#   These two commands are equivalent and demonstrate building in a
4911723Sar4jc@virginia.edu#   directory outside of the source tree.  The '-C' option tells scons
5011723Sar4jc@virginia.edu#   to chdir to the specified directory to find this SConstruct file.
5112808Srobert.scheffel1@tu-dresden.de#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
5212808Srobert.scheffel1@tu-dresden.de#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
5312808Srobert.scheffel1@tu-dresden.de#
5412808Srobert.scheffel1@tu-dresden.de# You can use 'scons -H' to print scons options.  If you're in this
5512808Srobert.scheffel1@tu-dresden.de# 'm5' directory (or use -u or -C to tell scons where to find this
5612808Srobert.scheffel1@tu-dresden.de# file), you can use 'scons -h' to print all the M5-specific build
5711723Sar4jc@virginia.edu# options as well.
5811723Sar4jc@virginia.edu#
5911723Sar4jc@virginia.edu###################################################
6011723Sar4jc@virginia.edu
6111723Sar4jc@virginia.edu# Python library imports
6212808Srobert.scheffel1@tu-dresden.deimport sys
6312808Srobert.scheffel1@tu-dresden.deimport os
6412808Srobert.scheffel1@tu-dresden.de
6512808Srobert.scheffel1@tu-dresden.de# Check for recent-enough Python and SCons versions
6612808Srobert.scheffel1@tu-dresden.deEnsurePythonVersion(2,3)
6712808Srobert.scheffel1@tu-dresden.de
6811723Sar4jc@virginia.edu# Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
6911723Sar4jc@virginia.edu# 3-element version number.
7011723Sar4jc@virginia.edumin_scons_version = (0,96,91)
7111723Sar4jc@virginia.edutry:
7211723Sar4jc@virginia.edu    EnsureSConsVersion(*min_scons_version)
7311723Sar4jc@virginia.eduexcept:
7411723Sar4jc@virginia.edu    print "Error checking current SCons version."
7511723Sar4jc@virginia.edu    print "SCons", ".".join(map(str,min_scons_version)), "or greater required."
7611723Sar4jc@virginia.edu    Exit(2)
7711723Sar4jc@virginia.edu    
7811723Sar4jc@virginia.edu
7911723Sar4jc@virginia.edu# The absolute path to the current directory (where this file lives).
8011723Sar4jc@virginia.eduROOT = Dir('.').abspath
8111723Sar4jc@virginia.edu
8211723Sar4jc@virginia.edu# Paths to the M5 and external source trees.
8311723Sar4jc@virginia.eduSRCDIR = os.path.join(ROOT, 'src')
8411723Sar4jc@virginia.edu
8511723Sar4jc@virginia.edu# tell python where to find m5 python code
8611723Sar4jc@virginia.edusys.path.append(os.path.join(ROOT, 'src/python'))
8711723Sar4jc@virginia.edu
8811723Sar4jc@virginia.edu###################################################
8911723Sar4jc@virginia.edu#
9011723Sar4jc@virginia.edu# Figure out which configurations to set up based on the path(s) of
9111723Sar4jc@virginia.edu# the target(s).
9211723Sar4jc@virginia.edu#
9311723Sar4jc@virginia.edu###################################################
9411723Sar4jc@virginia.edu
9511723Sar4jc@virginia.edu# Find default configuration & binary.
9611723Sar4jc@virginia.eduDefault(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
9711723Sar4jc@virginia.edu
9811723Sar4jc@virginia.edu# Ask SCons which directory it was invoked from.
9911723Sar4jc@virginia.edulaunch_dir = GetLaunchDir()
10011723Sar4jc@virginia.edu
10111723Sar4jc@virginia.edu# Make targets relative to invocation directory
10211723Sar4jc@virginia.eduabs_targets = map(lambda x: os.path.normpath(os.path.join(launch_dir, str(x))),
10311723Sar4jc@virginia.edu                  BUILD_TARGETS)
10411723Sar4jc@virginia.edu
10511723Sar4jc@virginia.edu# helper function: find last occurrence of element in list
10611723Sar4jc@virginia.edudef rfind(l, elt, offs = -1):
10711723Sar4jc@virginia.edu    for i in range(len(l)+offs, 0, -1):
108        if l[i] == elt:
109            return i
110    raise ValueError, "element not found"
111
112# Each target must have 'build' in the interior of the path; the
113# directory below this will determine the build parameters.  For
114# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
115# recognize that ALPHA_SE specifies the configuration because it
116# follow 'build' in the bulid path.
117
118# Generate a list of the unique build roots and configs that the
119# collected targets reference.
120build_paths = []
121build_root = None
122for t in abs_targets:
123    path_dirs = t.split('/')
124    try:
125        build_top = rfind(path_dirs, 'build', -2)
126    except:
127        print "Error: no non-leaf 'build' dir found on target path", t
128        Exit(1)
129    this_build_root = os.path.join('/',*path_dirs[:build_top+1])
130    if not build_root:
131        build_root = this_build_root
132    else:
133        if this_build_root != build_root:
134            print "Error: build targets not under same build root\n"\
135                  "  %s\n  %s" % (build_root, this_build_root)
136            Exit(1)
137    build_path = os.path.join('/',*path_dirs[:build_top+2])
138    if build_path not in build_paths:
139        build_paths.append(build_path)
140
141###################################################
142#
143# Set up the default build environment.  This environment is copied
144# and modified according to each selected configuration.
145#
146###################################################
147
148env = Environment(ENV = os.environ,  # inherit user's environment vars
149                  ROOT = ROOT,
150                  SRCDIR = SRCDIR)
151
152env.SConsignFile("sconsign")
153
154# I waffle on this setting... it does avoid a few painful but
155# unnecessary builds, but it also seems to make trivial builds take
156# noticeably longer.
157if False:
158    env.TargetSignatures('content')
159
160# M5_PLY is used by isa_parser.py to find the PLY package.
161env.Append(ENV = { 'M5_PLY' : Dir('ext/ply') })
162
163# Set up default C++ compiler flags
164env.Append(CCFLAGS='-pipe')
165env.Append(CCFLAGS='-fno-strict-aliasing')
166env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
167if sys.platform == 'cygwin':
168    # cygwin has some header file issues...
169    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
170env.Append(CPPPATH=[Dir('ext/dnet')])
171
172# Default libraries
173env.Append(LIBS=['z'])
174
175# Platform-specific configuration.  Note again that we assume that all
176# builds under a given build root run on the same host platform.
177conf = Configure(env,
178                 conf_dir = os.path.join(build_root, '.scons_config'),
179                 log_file = os.path.join(build_root, 'scons_config.log'))
180
181# Check for <fenv.h> (C99 FP environment control)
182have_fenv = conf.CheckHeader('fenv.h', '<>')
183if not have_fenv:
184    print "Warning: Header file <fenv.h> not found."
185    print "         This host has no IEEE FP rounding mode control."
186
187# Check for mysql.
188mysql_config = WhereIs('mysql_config')
189have_mysql = mysql_config != None
190
191# Check MySQL version.
192if have_mysql:
193    mysql_version = os.popen(mysql_config + ' --version').read()
194    mysql_version = mysql_version.split('.')
195    mysql_major = int(mysql_version[0])
196    mysql_minor = int(mysql_version[1])
197    # This version check is probably overly conservative, but it deals
198    # with the versions we have installed.
199    if mysql_major < 4 or (mysql_major == 4 and mysql_minor < 1):
200        print "Warning: MySQL v4.1 or newer required."
201        have_mysql = False
202
203# Set up mysql_config commands.
204if have_mysql:
205    mysql_config_include = mysql_config + ' --include'
206    if os.system(mysql_config_include + ' > /dev/null') != 0:
207        # older mysql_config versions don't support --include, use
208        # --cflags instead
209        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
210    # This seems to work in all versions
211    mysql_config_libs = mysql_config + ' --libs'
212
213env = conf.Finish()
214
215# Define the universe of supported ISAs
216env['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
217
218# Define the universe of supported CPU models
219env['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
220                       'FullCPU', 'AlphaFullCPU']
221
222# Sticky options get saved in the options file so they persist from
223# one invocation to the next (unless overridden, in which case the new
224# value becomes sticky).
225sticky_opts = Options(args=ARGUMENTS)
226sticky_opts.AddOptions(
227    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env['ALL_ISA_LIST']),
228    BoolOption('FULL_SYSTEM', 'Full-system support', False),
229    # There's a bug in scons 0.96.1 that causes ListOptions with list
230    # values (more than one value) not to be able to be restored from
231    # a saved option file.  If this causes trouble then upgrade to
232    # scons 0.96.90 or later.
233    ListOption('CPU_MODELS', 'CPU models', 'AtomicSimpleCPU,TimingSimpleCPU',
234               env['ALL_CPU_LIST']),
235    BoolOption('ALPHA_TLASER',
236               'Model Alpha TurboLaser platform (vs. Tsunami)', False),
237    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
238    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
239               False),
240    BoolOption('SS_COMPATIBLE_FP',
241               'Make floating-point results compatible with SimpleScalar',
242               False),
243    BoolOption('USE_SSE2',
244               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
245               False),
246    BoolOption('STATS_BINNING', 'Bin statistics by CPU mode', have_mysql),
247    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
248    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
249    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
250    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
251    BoolOption('BATCH', 'Use batch pool for build and tests', False),
252    ('BATCH_CMD', 'Batch pool submission command name', 'qdo')
253    )
254
255# Non-sticky options only apply to the current build.
256nonsticky_opts = Options(args=ARGUMENTS)
257nonsticky_opts.AddOptions(
258    BoolOption('update_ref', 'Update test reference outputs', False)
259    )
260
261# These options get exported to #defines in config/*.hh (see m5/SConscript).
262env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
263                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
264                     'STATS_BINNING']
265
266# Define a handy 'no-op' action
267def no_action(target, source, env):
268    return 0
269
270env.NoAction = Action(no_action, None)
271
272###################################################
273#
274# Define a SCons builder for configuration flag headers.
275#
276###################################################
277
278# This function generates a config header file that #defines the
279# option symbol to the current option setting (0 or 1).  The source
280# operands are the name of the option and a Value node containing the
281# value of the option.
282def build_config_file(target, source, env):
283    (option, value) = [s.get_contents() for s in source]
284    f = file(str(target[0]), 'w')
285    print >> f, '#define', option, value
286    f.close()
287    return None
288
289# Generate the message to be printed when building the config file.
290def build_config_file_string(target, source, env):
291    (option, value) = [s.get_contents() for s in source]
292    return "Defining %s as %s in %s." % (option, value, target[0])
293
294# Combine the two functions into a scons Action object.
295config_action = Action(build_config_file, build_config_file_string)
296
297# The emitter munges the source & target node lists to reflect what
298# we're really doing.
299def config_emitter(target, source, env):
300    # extract option name from Builder arg
301    option = str(target[0])
302    # True target is config header file
303    target = os.path.join('config', option.lower() + '.hh')
304    # Force value to 0/1 even if it's a Python bool
305    val = int(eval(str(env[option])))
306    # Sources are option name & value (packaged in SCons Value nodes)
307    return ([target], [Value(option), Value(val)])
308
309config_builder = Builder(emitter = config_emitter, action = config_action)
310
311env.Append(BUILDERS = { 'ConfigFile' : config_builder })
312
313# base help text
314help_text = '''
315Usage: scons [scons options] [build options] [target(s)]
316
317'''
318
319# libelf build is shared across all configs in the build root.
320env.SConscript('ext/libelf/SConscript',
321               build_dir = os.path.join(build_root, 'libelf'),
322               exports = 'env')
323
324###################################################
325#
326# Define build environments for selected configurations.
327#
328###################################################
329
330# rename base env
331base_env = env
332
333for build_path in build_paths:
334    print "Building in", build_path
335    # build_dir is the tail component of build path, and is used to
336    # determine the build parameters (e.g., 'ALPHA_SE')
337    (build_root, build_dir) = os.path.split(build_path)
338    # Make a copy of the build-root environment to use for this config.
339    env = base_env.Copy()
340
341    # Set env options according to the build directory config.
342    sticky_opts.files = []
343    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
344    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
345    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
346    current_opts_file = os.path.join(build_root, 'options', build_dir)
347    if os.path.isfile(current_opts_file):
348        sticky_opts.files.append(current_opts_file)
349        print "Using saved options file %s" % current_opts_file
350    else:
351        # Build dir-specific options file doesn't exist.
352
353        # Make sure the directory is there so we can create it later
354        opt_dir = os.path.dirname(current_opts_file)
355        if not os.path.isdir(opt_dir):
356            os.mkdir(opt_dir)
357
358        # Get default build options from source tree.  Options are
359        # normally determined by name of $BUILD_DIR, but can be
360        # overriden by 'default=' arg on command line.
361        default_opts_file = os.path.join('build_opts',
362                                         ARGUMENTS.get('default', build_dir))
363        if os.path.isfile(default_opts_file):
364            sticky_opts.files.append(default_opts_file)
365            print "Options file %s not found,\n  using defaults in %s" \
366                  % (current_opts_file, default_opts_file)
367        else:
368            print "Error: cannot find options file %s or %s" \
369                  % (current_opts_file, default_opts_file)
370            Exit(1)
371
372    # Apply current option settings to env
373    sticky_opts.Update(env)
374    nonsticky_opts.Update(env)
375
376    help_text += "Sticky options for %s:\n" % build_dir \
377                 + sticky_opts.GenerateHelpText(env) \
378                 + "\nNon-sticky options for %s:\n" % build_dir \
379                 + nonsticky_opts.GenerateHelpText(env)
380
381    # Process option settings.
382
383    if not have_fenv and env['USE_FENV']:
384        print "Warning: <fenv.h> not available; " \
385              "forcing USE_FENV to False in", build_dir + "."
386        env['USE_FENV'] = False
387
388    if not env['USE_FENV']:
389        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
390        print "         FP results may deviate slightly from other platforms."
391
392    if env['EFENCE']:
393        env.Append(LIBS=['efence'])
394
395    if env['USE_MYSQL']:
396        if not have_mysql:
397            print "Warning: MySQL not available; " \
398                  "forcing USE_MYSQL to False in", build_dir + "."
399            env['USE_MYSQL'] = False
400        else:
401            print "Compiling in", build_dir, "with MySQL support."
402            env.ParseConfig(mysql_config_libs)
403            env.ParseConfig(mysql_config_include)
404
405    # Save sticky option settings back to current options file
406    sticky_opts.Save(current_opts_file, env)
407
408    # Do this after we save setting back, or else we'll tack on an
409    # extra 'qdo' every time we run scons.
410    if env['BATCH']:
411        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
412        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
413
414    if env['USE_SSE2']:
415        env.Append(CCFLAGS='-msse2')
416
417    # The m5/SConscript file sets up the build rules in 'env' according
418    # to the configured options.  It returns a list of environments,
419    # one for each variant build (debug, opt, etc.)
420    envList = SConscript('src/SConscript', build_dir = build_path,
421                         exports = 'env', duplicate = False)
422
423    # Set up the regression tests for each build.
424#    for e in envList:
425#        SConscript('m5-test/SConscript',
426#                   build_dir = os.path.join(build_dir, 'test', e.Label),
427#                   exports = { 'env' : e }, duplicate = False)
428
429Help(help_text)
430
431###################################################
432#
433# Let SCons do its thing.  At this point SCons will use the defined
434# build environments to build the requested targets.
435#
436###################################################
437
438