SConstruct revision 9551:f867e530f39b
17893SN/A# -*- mode:python -*-
27893SN/A
37893SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
48825Snilay@cs.wisc.edu# Copyright (c) 2009 The Hewlett-Packard Development Company
57893SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
67893SN/A# All rights reserved.
77893SN/A#
87893SN/A# Redistribution and use in source and binary forms, with or without
97893SN/A# modification, are permitted provided that the following conditions are
107893SN/A# met: redistributions of source code must retain the above copyright
119885Sstever@gmail.com# notice, this list of conditions and the following disclaimer;
128825Snilay@cs.wisc.edu# redistributions in binary form must reproduce the above copyright
139885Sstever@gmail.com# notice, this list of conditions and the following disclaimer in the
149885Sstever@gmail.com# documentation and/or other materials provided with the distribution;
158825Snilay@cs.wisc.edu# neither the name of the copyright holders nor the names of its
168825Snilay@cs.wisc.edu# contributors may be used to endorse or promote products derived from
178825Snilay@cs.wisc.edu# this software without specific prior written permission.
189449SAli.Saidi@ARM.com#
199449SAli.Saidi@ARM.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
208464SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
218721SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
228825Snilay@cs.wisc.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
238825Snilay@cs.wisc.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
247935SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
257935SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
267935SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
277935SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
287935SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
297935SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
307935SN/A#
318983Snate@binkert.org# Authors: Steve Reinhardt
327893SN/A#          Nathan Binkert
339885Sstever@gmail.com
349885Sstever@gmail.com###################################################
359885Sstever@gmail.com#
369885Sstever@gmail.com# SCons top-level build description (SConstruct) file.
379885Sstever@gmail.com#
387893SN/A# While in this directory ('gem5'), just type 'scons' to build the default
397893SN/A# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
409885Sstever@gmail.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
417893SN/A# the optimized full-system version).
427893SN/A#
438241SN/A# You can build gem5 in a different directory as long as there is a
448241SN/A# 'build/<CONFIG>' somewhere along the target path.  The build system
457893SN/A# expects that all configs under the same build directory are being
467893SN/A# built for the same host system.
477893SN/A#
487893SN/A# Examples:
499481Snilay@cs.wisc.edu#
507893SN/A#   The following two commands are equivalent.  The '-u' option tells
517893SN/A#   scons to search up the directory tree for this SConstruct file.
529885Sstever@gmail.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
537893SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
547893SN/A#
557893SN/A#   The following two commands are equivalent and demonstrate building
567893SN/A#   in a directory outside of the source tree.  The '-C' option tells
577893SN/A#   scons to chdir to the specified directory to find this SConstruct
587893SN/A#   file.
597893SN/A#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
607893SN/A#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
617893SN/A#
627893SN/A# You can use 'scons -H' to print scons options.  If you're in this
637893SN/A# 'gem5' directory (or use -u or -C to tell scons where to find this
648825Snilay@cs.wisc.edu# file), you can use 'scons -h' to print all the gem5-specific build
657893SN/A# options as well.
667893SN/A#
677893SN/A###################################################
687893SN/A
697893SN/A# Check for recent-enough Python and SCons versions.
707893SN/Atry:
717893SN/A    # Really old versions of scons only take two options for the
727893SN/A    # function, so check once without the revision and once with the
737893SN/A    # revision, the first instance will fail for stuff other than
747893SN/A    # 0.98, and the second will fail for 0.98.0
757893SN/A    EnsureSConsVersion(0, 98)
767893SN/A    EnsureSConsVersion(0, 98, 1)
777893SN/Aexcept SystemExit, e:
788825Snilay@cs.wisc.edu    print """
799449SAli.Saidi@ARM.comFor more details, see:
807893SN/A    http://gem5.org/Dependencies
817893SN/A"""
827893SN/A    raise
837893SN/A
847893SN/A# We ensure the python version early because we have stuff that
857893SN/A# requires python 2.4
867893SN/Atry:
878728SN/A    EnsurePythonVersion(2, 4)
887893SN/Aexcept SystemExit, e:
897893SN/A    print """
907893SN/AYou can use a non-default installation of the Python interpreter by
917893SN/Aeither (1) rearranging your PATH so that scons finds the non-default
927893SN/A'python' first or (2) explicitly invoking an alternative interpreter
937893SN/Aon the scons script.
948825Snilay@cs.wisc.edu
957893SN/AFor more details, see:
967893SN/A    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
977893SN/A"""
987893SN/A    raise
997893SN/A
1007893SN/A# Global Python includes
1019885Sstever@gmail.comimport os
1027893SN/Aimport re
1037893SN/Aimport subprocess
1047893SN/Aimport sys
1057893SN/A
1067893SN/Afrom os import mkdir, environ
1077893SN/Afrom os.path import abspath, basename, dirname, expanduser, normpath
1087893SN/Afrom os.path import exists,  isdir, isfile
1097893SN/Afrom os.path import join as joinpath, split as splitpath
1107893SN/A
1117893SN/A# SCons includes
1128521SN/Aimport SCons
1139449SAli.Saidi@ARM.comimport SCons.Node
1147893SN/A
1157893SN/Aextra_python_paths = [
1167893SN/A    Dir('src/python').srcnode().abspath, # gem5 includes
1177893SN/A    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1187893SN/A    ]
1197893SN/A
1207893SN/Asys.path[1:1] = extra_python_paths
1217893SN/A
1227893SN/Afrom m5.util import compareVersions, readCommand
1239885Sstever@gmail.comfrom m5.util.terminal import get_termcap
1249885Sstever@gmail.com
1259885Sstever@gmail.comhelp_texts = {
1269885Sstever@gmail.com    "options" : "",
1279885Sstever@gmail.com    "global_vars" : "",
1289481Snilay@cs.wisc.edu    "local_vars" : ""
1299481Snilay@cs.wisc.edu}
1309481Snilay@cs.wisc.edu
1319481Snilay@cs.wisc.eduExport("help_texts")
1329481Snilay@cs.wisc.edu
1339481Snilay@cs.wisc.edu
1349481Snilay@cs.wisc.edu# There's a bug in scons in that (1) by default, the help texts from
1359481Snilay@cs.wisc.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1369481Snilay@cs.wisc.edu# and (2) you can override the help displayed by 'scons -h' using the
1379481Snilay@cs.wisc.edu# Help() function, but these two features are incompatible: once
1389481Snilay@cs.wisc.edu# you've overridden the help text using Help(), there's no way to get
1399481Snilay@cs.wisc.edu# at the help texts from AddOptions.  See:
1409481Snilay@cs.wisc.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1419481Snilay@cs.wisc.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1429481Snilay@cs.wisc.edu# This hack lets us extract the help text from AddOptions and
1439481Snilay@cs.wisc.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1447893SN/A# we can just use AddOption directly.
1457893SN/Adef AddLocalOption(*args, **kwargs):
1469885Sstever@gmail.com    col_width = 30
1478983Snate@binkert.org
1487893SN/A    help = "  " + ", ".join(args)
1499885Sstever@gmail.com    if "help" in kwargs:
1507893SN/A        length = len(help)
1519348SAli.Saidi@ARM.com        if length >= col_width:
1528200SN/A            help += "\n" + " " * col_width
1537893SN/A        else:
1549348SAli.Saidi@ARM.com            help += " " * (col_width - length)
1557893SN/A        help += kwargs["help"]
1568835SAli.Saidi@ARM.com    help_texts["options"] += help + "\n"
1579348SAli.Saidi@ARM.com
1587893SN/A    AddOption(*args, **kwargs)
1598835SAli.Saidi@ARM.com
1609885Sstever@gmail.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1617893SN/A               help="Add color to abbreviated scons output")
1627893SN/AAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1637893SN/A               help="Don't add color to abbreviated scons output")
1647893SN/AAddLocalOption('--default', dest='default', type='string', action='store',
1658983Snate@binkert.org               help='Override which build_opts file to use for defaults')
1667893SN/AAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1679885Sstever@gmail.com               help='Disable style checking hooks')
1689885Sstever@gmail.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1699885Sstever@gmail.com               help='Disable Link-Time Optimization for fast')
1709885Sstever@gmail.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1719885Sstever@gmail.com               help='Update test reference outputs')
1729885Sstever@gmail.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1739885Sstever@gmail.com               help='Print full tool command lines')
1749885Sstever@gmail.com
1757893SN/Atermcap = get_termcap(GetOption('use_colors'))
1767893SN/A
1778825Snilay@cs.wisc.edu########################################################################
1787893SN/A#
1798825Snilay@cs.wisc.edu# Set up the main build environment.
1808825Snilay@cs.wisc.edu#
1818825Snilay@cs.wisc.edu########################################################################
1828825Snilay@cs.wisc.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1839885Sstever@gmail.com                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1849885Sstever@gmail.com                 'RANLIB', 'SWIG' ])
1858825Snilay@cs.wisc.edu
1868983Snate@binkert.orguse_prefixes = [
1877893SN/A    "M5",           # M5 configuration (e.g., path to kernels)
1887893SN/A    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
1897893SN/A    "CCACHE_",      # ccache (caching compiler wrapper) configuration
1907893SN/A    "CCC_",         # clang static analyzer configuration
1917893SN/A    ]
1927893SN/A
1937893SN/Ause_env = {}
1947893SN/Afor key,val in os.environ.iteritems():
1957893SN/A    if key in use_vars or \
1967893SN/A            any([key.startswith(prefix) for prefix in use_prefixes]):
1977893SN/A        use_env[key] = val
1987893SN/A
1997893SN/Amain = Environment(ENV=use_env)
2007893SN/Amain.Decider('MD5-timestamp')
2017893SN/Amain.root = Dir(".")         # The current directory (where this file lives).
2027893SN/Amain.srcdir = Dir("src")     # The source directory
2037893SN/A
2047893SN/Amain_dict_keys = main.Dictionary().keys()
2057893SN/A
2067893SN/A# Check that we have a C/C++ compiler
2077893SN/Aif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2087893SN/A    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2097893SN/A    Exit(1)
2107893SN/A
2117893SN/A# Check that swig is present
2127893SN/Aif not 'SWIG' in main_dict_keys:
2137893SN/A    print "swig is not installed (package swig on Ubuntu and RedHat)"
2147893SN/A    Exit(1)
2157893SN/A
2167893SN/A# add useful python code PYTHONPATH so it can be used by subprocesses
2177893SN/A# as well
2187893SN/Amain.AppendENVPath('PYTHONPATH', extra_python_paths)
2197893SN/A
2207893SN/A########################################################################
2217893SN/A#
2227893SN/A# Mercurial Stuff.
2237893SN/A#
2247893SN/A# If the gem5 directory is a mercurial repository, we should do some
2257893SN/A# extra things.
2267893SN/A#
2277893SN/A########################################################################
2287893SN/A
2297893SN/Ahgdir = main.root.Dir(".hg")
2307893SN/A
2317893SN/Amercurial_style_message = """
2327893SN/AYou're missing the gem5 style hook, which automatically checks your code
2337893SN/Aagainst the gem5 style rules on hg commit and qrefresh commands.  This
2347893SN/Ascript will now install the hook in your .hg/hgrc file.
2357893SN/APress enter to continue, or ctrl-c to abort: """
2367893SN/A
2377893SN/Amercurial_style_hook = """
2387893SN/A# The following lines were automatically added by gem5/SConstruct
2397893SN/A# to provide the gem5 style-checking hooks
2407893SN/A[extensions]
2417893SN/Astyle = %s/util/style.py
2427893SN/A
2437893SN/A[hooks]
2447893SN/Apretxncommit.style = python:style.check_style
2457893SN/Apre-qrefresh.style = python:style.check_style
2467893SN/A# End of SConstruct additions
2477893SN/A
2487893SN/A""" % (main.root.abspath)
2497893SN/A
2507893SN/Amercurial_lib_not_found = """
2517893SN/AMercurial libraries cannot be found, ignoring style hook.  If
2527893SN/Ayou are a gem5 developer, please fix this and run the style
2537893SN/Ahook. It is important.
2547893SN/A"""
2557893SN/A
2567893SN/A# Check for style hook and prompt for installation if it's not there.
2577893SN/A# Skip this if --ignore-style was specified, there's no .hg dir to
2587893SN/A# install a hook in, or there's no interactive terminal to prompt.
2597893SN/Aif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2607893SN/A    style_hook = True
2617893SN/A    try:
2627893SN/A        from mercurial import ui
2637893SN/A        ui = ui.ui()
2647893SN/A        ui.readconfig(hgdir.File('hgrc').abspath)
2657893SN/A        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2667893SN/A                     ui.config('hooks', 'pre-qrefresh.style', None)
2677893SN/A    except ImportError:
2687893SN/A        print mercurial_lib_not_found
2697893SN/A
2707893SN/A    if not style_hook:
2717893SN/A        print mercurial_style_message,
2727893SN/A        # continue unless user does ctrl-c/ctrl-d etc.
2737893SN/A        try:
2747893SN/A            raw_input()
2757893SN/A        except:
2767893SN/A            print "Input exception, exiting scons.\n"
2777893SN/A            sys.exit(1)
2787893SN/A        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2797893SN/A        print "Adding style hook to", hgrc_path, "\n"
2807893SN/A        try:
2817893SN/A            hgrc = open(hgrc_path, 'a')
2827893SN/A            hgrc.write(mercurial_style_hook)
2837893SN/A            hgrc.close()
2847893SN/A        except:
2857893SN/A            print "Error updating", hgrc_path
2867893SN/A            sys.exit(1)
2877893SN/A
2887893SN/A
2897893SN/A###################################################
2907893SN/A#
2917893SN/A# Figure out which configurations to set up based on the path(s) of
2927893SN/A# the target(s).
2937893SN/A#
2947893SN/A###################################################
2957893SN/A
2967893SN/A# Find default configuration & binary.
2977893SN/ADefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2987893SN/A
2997893SN/A# helper function: find last occurrence of element in list
3007893SN/Adef rfind(l, elt, offs = -1):
3017893SN/A    for i in range(len(l)+offs, 0, -1):
3027893SN/A        if l[i] == elt:
3037893SN/A            return i
3047893SN/A    raise ValueError, "element not found"
3057893SN/A
3067893SN/A# Take a list of paths (or SCons Nodes) and return a list with all
3077893SN/A# paths made absolute and ~-expanded.  Paths will be interpreted
3087893SN/A# relative to the launch directory unless a different root is provided
3097893SN/Adef makePathListAbsolute(path_list, root=GetLaunchDir()):
3107893SN/A    return [abspath(joinpath(root, expanduser(str(p))))
3117893SN/A            for p in path_list]
3127893SN/A
3137893SN/A# Each target must have 'build' in the interior of the path; the
3147893SN/A# directory below this will determine the build parameters.  For
3157893SN/A# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3167893SN/A# recognize that ALPHA_SE specifies the configuration because it
3177893SN/A# follow 'build' in the build path.
3187893SN/A
3197893SN/A# The funky assignment to "[:]" is needed to replace the list contents
3207893SN/A# in place rather than reassign the symbol to a new list, which
3217893SN/A# doesn't work (obviously!).
3227893SN/ABUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3237893SN/A
3247893SN/A# Generate a list of the unique build roots and configs that the
3257893SN/A# collected targets reference.
3267893SN/Avariant_paths = []
3277893SN/Abuild_root = None
3287893SN/Afor t in BUILD_TARGETS:
3297893SN/A    path_dirs = t.split('/')
3307893SN/A    try:
3317893SN/A        build_top = rfind(path_dirs, 'build', -2)
3327893SN/A    except:
3337893SN/A        print "Error: no non-leaf 'build' dir found on target path", t
3347893SN/A        Exit(1)
3357893SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3367893SN/A    if not build_root:
3377893SN/A        build_root = this_build_root
3387893SN/A    else:
3397893SN/A        if this_build_root != build_root:
3407893SN/A            print "Error: build targets not under same build root\n"\
3417893SN/A                  "  %s\n  %s" % (build_root, this_build_root)
3427893SN/A            Exit(1)
3437893SN/A    variant_path = joinpath('/',*path_dirs[:build_top+2])
3447893SN/A    if variant_path not in variant_paths:
3457893SN/A        variant_paths.append(variant_path)
3467893SN/A
3477893SN/A# Make sure build_root exists (might not if this is the first build there)
3487893SN/Aif not isdir(build_root):
3497893SN/A    mkdir(build_root)
3507893SN/Amain['BUILDROOT'] = build_root
3517893SN/A
3527893SN/AExport('main')
3537893SN/A
3547893SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
3557893SN/A
3567893SN/A# Default duplicate option is to use hard links, but this messes up
3577893SN/A# when you use emacs to edit a file in the target dir, as emacs moves
3587893SN/A# file to file~ then copies to file, breaking the link.  Symbolic
3597893SN/A# (soft) links work better.
3607893SN/Amain.SetOption('duplicate', 'soft-copy')
3617893SN/A
3627893SN/A#
3637893SN/A# Set up global sticky variables... these are common to an entire build
3647893SN/A# tree (not specific to a particular build like ALPHA_SE)
3657893SN/A#
3667893SN/A
3677893SN/Aglobal_vars_file = joinpath(build_root, 'variables.global')
3687893SN/A
3697893SN/Aglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3707893SN/A
3717893SN/Aglobal_vars.AddVariables(
3727893SN/A    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3737893SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3747893SN/A    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3757893SN/A    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3767893SN/A    ('BATCH', 'Use batch pool for build and tests', False),
3777893SN/A    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3787893SN/A    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3797893SN/A    ('EXTRAS', 'Add extra directories to the compilation', '')
3807893SN/A    )
3817893SN/A
3827893SN/A# Update main environment with values from ARGUMENTS & global_vars_file
3837893SN/Aglobal_vars.Update(main)
3847893SN/Ahelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3857893SN/A
3867893SN/A# Save sticky variable settings back to current variables file
3877893SN/Aglobal_vars.Save(global_vars_file, main)
3887893SN/A
3897893SN/A# Parse EXTRAS variable to build list of all directories where we're
3907893SN/A# look for sources etc.  This list is exported as extras_dir_list.
3917893SN/Abase_dir = main.srcdir.abspath
3927893SN/Aif main['EXTRAS']:
3937893SN/A    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3947893SN/Aelse:
3957893SN/A    extras_dir_list = []
3967893SN/A
3977893SN/AExport('base_dir')
3987893SN/AExport('extras_dir_list')
3997893SN/A
4007893SN/A# the ext directory should be on the #includes path
4017893SN/Amain.Append(CPPPATH=[Dir('ext')])
4027893SN/A
4037893SN/Adef strip_build_path(path, env):
4047893SN/A    path = str(path)
4057893SN/A    variant_base = env['BUILDROOT'] + os.path.sep
4067893SN/A    if path.startswith(variant_base):
4077893SN/A        path = path[len(variant_base):]
4087893SN/A    elif path.startswith('build/'):
4097893SN/A        path = path[6:]
4107893SN/A    return path
4117893SN/A
4127893SN/A# Generate a string of the form:
4137893SN/A#   common/path/prefix/src1, src2 -> tgt1, tgt2
4147893SN/A# to print while building.
4157893SN/Aclass Transform(object):
4167893SN/A    # all specific color settings should be here and nowhere else
4177893SN/A    tool_color = termcap.Normal
4187893SN/A    pfx_color = termcap.Yellow
4197893SN/A    srcs_color = termcap.Yellow + termcap.Bold
4207893SN/A    arrow_color = termcap.Blue + termcap.Bold
4217893SN/A    tgts_color = termcap.Yellow + termcap.Bold
4227893SN/A
4237893SN/A    def __init__(self, tool, max_sources=99):
4247893SN/A        self.format = self.tool_color + (" [%8s] " % tool) \
4257893SN/A                      + self.pfx_color + "%s" \
4267893SN/A                      + self.srcs_color + "%s" \
4277893SN/A                      + self.arrow_color + " -> " \
4287893SN/A                      + self.tgts_color + "%s" \
4297893SN/A                      + termcap.Normal
4307893SN/A        self.max_sources = max_sources
4317893SN/A
4327893SN/A    def __call__(self, target, source, env, for_signature=None):
4337893SN/A        # truncate source list according to max_sources param
4347893SN/A        source = source[0:self.max_sources]
4357893SN/A        def strip(f):
4367893SN/A            return strip_build_path(str(f), env)
4377893SN/A        if len(source) > 0:
4387893SN/A            srcs = map(strip, source)
4397893SN/A        else:
4407893SN/A            srcs = ['']
4417893SN/A        tgts = map(strip, target)
4427893SN/A        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4437893SN/A        # operation that has nothing to do with paths.
4447893SN/A        com_pfx = os.path.commonprefix(srcs + tgts)
4457893SN/A        com_pfx_len = len(com_pfx)
4467893SN/A        if com_pfx:
4477893SN/A            # do some cleanup and sanity checking on common prefix
4487893SN/A            if com_pfx[-1] == ".":
4497893SN/A                # prefix matches all but file extension: ok
4507893SN/A                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4517893SN/A                com_pfx = com_pfx[0:-1]
4527893SN/A            elif com_pfx[-1] == "/":
4539885Sstever@gmail.com                # common prefix is directory path: OK
4548983Snate@binkert.org                pass
4557893SN/A            else:
4569885Sstever@gmail.com                src0_len = len(srcs[0])
4577893SN/A                tgt0_len = len(tgts[0])
4589348SAli.Saidi@ARM.com                if src0_len == com_pfx_len:
4598200SN/A                    # source is a substring of target, OK
4607893SN/A                    pass
4619348SAli.Saidi@ARM.com                elif tgt0_len == com_pfx_len:
4627893SN/A                    # target is a substring of source, need to back up to
4638835SAli.Saidi@ARM.com                    # avoid empty string on RHS of arrow
4649348SAli.Saidi@ARM.com                    sep_idx = com_pfx.rfind(".")
4657893SN/A                    if sep_idx != -1:
4668835SAli.Saidi@ARM.com                        com_pfx = com_pfx[0:sep_idx]
4679885Sstever@gmail.com                    else:
4687893SN/A                        com_pfx = ''
4697893SN/A                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4707893SN/A                    # still splitting at file extension: ok
4717893SN/A                    pass
4728983Snate@binkert.org                else:
4737893SN/A                    # probably a fluke; ignore it
4749885Sstever@gmail.com                    com_pfx = ''
4759885Sstever@gmail.com        # recalculate length in case com_pfx was modified
4769885Sstever@gmail.com        com_pfx_len = len(com_pfx)
4779885Sstever@gmail.com        def fmt(files):
4789885Sstever@gmail.com            f = map(lambda s: s[com_pfx_len:], files)
4799885Sstever@gmail.com            return ', '.join(f)
4809885Sstever@gmail.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4819885Sstever@gmail.com
4828825Snilay@cs.wisc.eduExport('Transform')
4838825Snilay@cs.wisc.edu
4849885Sstever@gmail.com# enable the regression script to use the termcap
4858825Snilay@cs.wisc.edumain['TERMCAP'] = termcap
4868825Snilay@cs.wisc.edu
4879213Snilay@cs.wisc.eduif GetOption('verbose'):
4888825Snilay@cs.wisc.edu    def MakeAction(action, string, *args, **kwargs):
4898983Snate@binkert.org        return Action(action, *args, **kwargs)
4908983Snate@binkert.orgelse:
4918983Snate@binkert.org    MakeAction = Action
4928825Snilay@cs.wisc.edu    main['CCCOMSTR']        = Transform("CC")
4939449SAli.Saidi@ARM.com    main['CXXCOMSTR']       = Transform("CXX")
4949449SAli.Saidi@ARM.com    main['ASCOMSTR']        = Transform("AS")
4959449SAli.Saidi@ARM.com    main['SWIGCOMSTR']      = Transform("SWIG")
4967893SN/A    main['ARCOMSTR']        = Transform("AR", 0)
4977893SN/A    main['LINKCOMSTR']      = Transform("LINK", 0)
4988825Snilay@cs.wisc.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4997893SN/A    main['M4COMSTR']        = Transform("M4")
5008825Snilay@cs.wisc.edu    main['SHCCCOMSTR']      = Transform("SHCC")
5018825Snilay@cs.wisc.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
5028825Snilay@cs.wisc.eduExport('MakeAction')
5038825Snilay@cs.wisc.edu
5049885Sstever@gmail.com# Initialize the Link-Time Optimization (LTO) flags
5059885Sstever@gmail.commain['LTO_CCFLAGS'] = []
5068825Snilay@cs.wisc.edumain['LTO_LDFLAGS'] = []
5078983Snate@binkert.org
5087893SN/ACXX_version = readCommand([main['CXX'],'--version'], exception=False)
5097893SN/ACXX_V = readCommand([main['CXX'],'-V'], exception=False)
5107893SN/A
5119885Sstever@gmail.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5128983Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5139348SAli.Saidi@ARM.comif main['GCC'] + main['CLANG'] > 1:
5149885Sstever@gmail.com    print 'Error: How can we have two at the same time?'
5157893SN/A    Exit(1)
5169348SAli.Saidi@ARM.com
5178200SN/A# Set up default C++ compiler flags
5187893SN/Aif main['GCC']:
5199348SAli.Saidi@ARM.com    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5207893SN/A    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5218835SAli.Saidi@ARM.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5229348SAli.Saidi@ARM.com    if compareVersions(gcc_version, "4.4") < 0:
5237893SN/A        print 'Error: gcc version 4.4 or newer required.'
5248835SAli.Saidi@ARM.com        print '       Installed version:', gcc_version
5259885Sstever@gmail.com        Exit(1)
5269348SAli.Saidi@ARM.com
5277893SN/A    main['GCC_VERSION'] = gcc_version
5287893SN/A    main.Append(CCFLAGS=['-pipe'])
5298983Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5308983Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5317893SN/A    main.Append(CXXFLAGS=['-Wmissing-field-initializers'])
5329885Sstever@gmail.com    main.Append(CXXFLAGS=['-std=c++0x'])
5339885Sstever@gmail.com
5349885Sstever@gmail.com    # Check for versions with bugs
5359885Sstever@gmail.com    if not compareVersions(gcc_version, '4.4.1') or \
5369885Sstever@gmail.com       not compareVersions(gcc_version, '4.4.2'):
5379885Sstever@gmail.com        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5389885Sstever@gmail.com        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5399885Sstever@gmail.com
5407893SN/A    # LTO support is only really working properly from 4.6 and beyond
5419039Sgblack@eecs.umich.edu    if compareVersions(gcc_version, '4.6') >= 0:
5429885Sstever@gmail.com        # Add the appropriate Link-Time Optimization (LTO) flags
5437893SN/A        # unless LTO is explicitly turned off. Note that these flags
5449583Snilay@cs.wisc.edu        # are only used by the fast target.
5457893SN/A        if not GetOption('no_lto'):
5469348SAli.Saidi@ARM.com            # Pass the LTO flag when compiling to produce GIMPLE
5478983Snate@binkert.org            # output, we merely create the flags here and only append
5488983Snate@binkert.org            # them later/
5497893SN/A            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5507893SN/A
5517893SN/A            # Use the same amount of jobs for LTO as we are running
5527893SN/A            # scons with, we hardcode the use of the linker plugin
5537893SN/A            # which requires either gold or GNU ld >= 2.21
5547893SN/A            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5557893SN/A                                   '-fuse-linker-plugin']
5569150SAli.Saidi@ARM.com
5577893SN/Aelif main['CLANG']:
5587893SN/A    # Check for a supported version of clang, >= 2.9 is needed to
5597893SN/A    # support similar features as gcc 4.4. See
5607893SN/A    # http://clang.llvm.org/cxx_status.html for details
5619885Sstever@gmail.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
5627893SN/A    clang_version_match = clang_version_re.match(CXX_version)
5639885Sstever@gmail.com    if (clang_version_match):
5647893SN/A        clang_version = clang_version_match.groups()[0]
5657893SN/A        if compareVersions(clang_version, "2.9") < 0:
5667893SN/A            print 'Error: clang version 2.9 or newer required.'
5677893SN/A            print '       Installed version:', clang_version
5687893SN/A            Exit(1)
5697893SN/A    else:
5707893SN/A        print 'Error: Unable to determine clang version.'
5717893SN/A        Exit(1)
5729885Sstever@gmail.com
5739885Sstever@gmail.com    main.Append(CCFLAGS=['-pipe'])
5749885Sstever@gmail.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5759885Sstever@gmail.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5769885Sstever@gmail.com    main.Append(CCFLAGS=['-Wno-tautological-compare'])
5777893SN/A    main.Append(CCFLAGS=['-Wno-self-assign'])
5789039Sgblack@eecs.umich.edu    # Ruby makes frequent use of extraneous parantheses in the printing
5799885Sstever@gmail.com    # of if-statements
5807893SN/A    main.Append(CCFLAGS=['-Wno-parentheses'])
5819583Snilay@cs.wisc.edu    main.Append(CXXFLAGS=['-Wmissing-field-initializers'])
5827893SN/A    main.Append(CXXFLAGS=['-std=c++0x'])
5839096Sandreas.hansson@arm.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5849150SAli.Saidi@ARM.com    # opposed to libstdc++ to make the transition from TR1 to
5858983Snate@binkert.org    # C++11. See http://libcxx.llvm.org. However, clang has chosen a
5867893SN/A    # strict implementation of the C++11 standard, and does not allow
5877893SN/A    # incomplete types in template arguments (besides unique_ptr and
5889348SAli.Saidi@ARM.com    # shared_ptr), and the libc++ STL containers create problems in
5899583Snilay@cs.wisc.edu    # combination with the current gem5 code. For now, we stick with
5909885Sstever@gmail.com    # libstdc++ and use the TR1 namespace.
5919348SAli.Saidi@ARM.com    # if sys.platform == "darwin":
5929885Sstever@gmail.com    #     main.Append(CXXFLAGS=['-stdlib=libc++'])
5939583Snilay@cs.wisc.edu
5949885Sstever@gmail.comelse:
5959885Sstever@gmail.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5969885Sstever@gmail.com    print "Don't know what compiler options to use for your compiler."
5979885Sstever@gmail.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5989885Sstever@gmail.com    print termcap.Yellow + '       version:' + termcap.Normal,
5998983Snate@binkert.org    if not CXX_version:
6009583Snilay@cs.wisc.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6017893SN/A               termcap.Normal
6029348SAli.Saidi@ARM.com    else:
6037893SN/A        print CXX_version.replace('\n', '<nl>')
6049348SAli.Saidi@ARM.com    print "       If you're trying to use a compiler other than GCC"
6059348SAli.Saidi@ARM.com    print "       or clang, there appears to be something wrong with your"
6069885Sstever@gmail.com    print "       environment."
6079885Sstever@gmail.com    print "       "
6089583Snilay@cs.wisc.edu    print "       If you are trying to use a compiler other than those listed"
6099583Snilay@cs.wisc.edu    print "       above you will need to ease fix SConstruct and "
6109583Snilay@cs.wisc.edu    print "       src/SConscript to support that compiler."
6119348SAli.Saidi@ARM.com    Exit(1)
6129348SAli.Saidi@ARM.com
6139583Snilay@cs.wisc.edu# Set up common yacc/bison flags (needed for Ruby)
6149583Snilay@cs.wisc.edumain['YACCFLAGS'] = '-d'
6159583Snilay@cs.wisc.edumain['YACCHXXFILESUFFIX'] = '.hh'
6169348SAli.Saidi@ARM.com
6179348SAli.Saidi@ARM.com# Do this after we save setting back, or else we'll tack on an
6188983Snate@binkert.org# extra 'qdo' every time we run scons.
6197893SN/Aif main['BATCH']:
6209885Sstever@gmail.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6219885Sstever@gmail.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6229885Sstever@gmail.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6239885Sstever@gmail.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
624    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
625
626if sys.platform == 'cygwin':
627    # cygwin has some header file issues...
628    main.Append(CCFLAGS=["-Wno-uninitialized"])
629
630# Check for the protobuf compiler
631protoc_version = readCommand([main['PROTOC'], '--version'],
632                             exception='').split()
633
634# First two words should be "libprotoc x.y.z"
635if len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
636    print termcap.Yellow + termcap.Bold + \
637        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
638        '         Please install protobuf-compiler for tracing support.' + \
639        termcap.Normal
640    main['PROTOC'] = False
641else:
642    # Based on the availability of the compress stream wrappers,
643    # require 2.1.0
644    min_protoc_version = '2.1.0'
645    if compareVersions(protoc_version[1], min_protoc_version) < 0:
646        print termcap.Yellow + termcap.Bold + \
647            'Warning: protoc version', min_protoc_version, \
648            'or newer required.\n' + \
649            '         Installed version:', protoc_version[1], \
650            termcap.Normal
651        main['PROTOC'] = False
652    else:
653        # Attempt to determine the appropriate include path and
654        # library path using pkg-config, that means we also need to
655        # check for pkg-config. Note that it is possible to use
656        # protobuf without the involvement of pkg-config. Later on we
657        # check go a library config check and at that point the test
658        # will fail if libprotobuf cannot be found.
659        if readCommand(['pkg-config', '--version'], exception=''):
660            try:
661                # Attempt to establish what linking flags to add for protobuf
662                # using pkg-config
663                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
664            except:
665                print termcap.Yellow + termcap.Bold + \
666                    'Warning: pkg-config could not get protobuf flags.' + \
667                    termcap.Normal
668
669# Check for SWIG
670if not main.has_key('SWIG'):
671    print 'Error: SWIG utility not found.'
672    print '       Please install (see http://www.swig.org) and retry.'
673    Exit(1)
674
675# Check for appropriate SWIG version
676swig_version = readCommand([main['SWIG'], '-version'], exception='').split()
677# First 3 words should be "SWIG Version x.y.z"
678if len(swig_version) < 3 or \
679        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
680    print 'Error determining SWIG version.'
681    Exit(1)
682
683min_swig_version = '1.3.34'
684if compareVersions(swig_version[2], min_swig_version) < 0:
685    print 'Error: SWIG version', min_swig_version, 'or newer required.'
686    print '       Installed version:', swig_version[2]
687    Exit(1)
688
689# Set up SWIG flags & scanner
690swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
691main.Append(SWIGFLAGS=swig_flags)
692
693# filter out all existing swig scanners, they mess up the dependency
694# stuff for some reason
695scanners = []
696for scanner in main['SCANNERS']:
697    skeys = scanner.skeys
698    if skeys == '.i':
699        continue
700
701    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
702        continue
703
704    scanners.append(scanner)
705
706# add the new swig scanner that we like better
707from SCons.Scanner import ClassicCPP as CPPScanner
708swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
709scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
710
711# replace the scanners list that has what we want
712main['SCANNERS'] = scanners
713
714# Add a custom Check function to the Configure context so that we can
715# figure out if the compiler adds leading underscores to global
716# variables.  This is needed for the autogenerated asm files that we
717# use for embedding the python code.
718def CheckLeading(context):
719    context.Message("Checking for leading underscore in global variables...")
720    # 1) Define a global variable called x from asm so the C compiler
721    #    won't change the symbol at all.
722    # 2) Declare that variable.
723    # 3) Use the variable
724    #
725    # If the compiler prepends an underscore, this will successfully
726    # link because the external symbol 'x' will be called '_x' which
727    # was defined by the asm statement.  If the compiler does not
728    # prepend an underscore, this will not successfully link because
729    # '_x' will have been defined by assembly, while the C portion of
730    # the code will be trying to use 'x'
731    ret = context.TryLink('''
732        asm(".globl _x; _x: .byte 0");
733        extern int x;
734        int main() { return x; }
735        ''', extension=".c")
736    context.env.Append(LEADING_UNDERSCORE=ret)
737    context.Result(ret)
738    return ret
739
740# Platform-specific configuration.  Note again that we assume that all
741# builds under a given build root run on the same host platform.
742conf = Configure(main,
743                 conf_dir = joinpath(build_root, '.scons_config'),
744                 log_file = joinpath(build_root, 'scons_config.log'),
745                 custom_tests = { 'CheckLeading' : CheckLeading })
746
747# Check for leading underscores.  Don't really need to worry either
748# way so don't need to check the return code.
749conf.CheckLeading()
750
751# Check if we should compile a 64 bit binary on Mac OS X/Darwin
752try:
753    import platform
754    uname = platform.uname()
755    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
756        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
757            main.Append(CCFLAGS=['-arch', 'x86_64'])
758            main.Append(CFLAGS=['-arch', 'x86_64'])
759            main.Append(LINKFLAGS=['-arch', 'x86_64'])
760            main.Append(ASFLAGS=['-arch', 'x86_64'])
761except:
762    pass
763
764# Recent versions of scons substitute a "Null" object for Configure()
765# when configuration isn't necessary, e.g., if the "--help" option is
766# present.  Unfortuantely this Null object always returns false,
767# breaking all our configuration checks.  We replace it with our own
768# more optimistic null object that returns True instead.
769if not conf:
770    def NullCheck(*args, **kwargs):
771        return True
772
773    class NullConf:
774        def __init__(self, env):
775            self.env = env
776        def Finish(self):
777            return self.env
778        def __getattr__(self, mname):
779            return NullCheck
780
781    conf = NullConf(main)
782
783# Find Python include and library directories for embedding the
784# interpreter.  For consistency, we will use the same Python
785# installation used to run scons (and thus this script).  If you want
786# to link in an alternate version, see above for instructions on how
787# to invoke scons with a different copy of the Python interpreter.
788from distutils import sysconfig
789
790py_getvar = sysconfig.get_config_var
791
792py_debug = getattr(sys, 'pydebug', False)
793py_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
794
795py_general_include = sysconfig.get_python_inc()
796py_platform_include = sysconfig.get_python_inc(plat_specific=True)
797py_includes = [ py_general_include ]
798if py_platform_include != py_general_include:
799    py_includes.append(py_platform_include)
800
801py_lib_path = [ py_getvar('LIBDIR') ]
802# add the prefix/lib/pythonX.Y/config dir, but only if there is no
803# shared library in prefix/lib/.
804if not py_getvar('Py_ENABLE_SHARED'):
805    py_lib_path.append(py_getvar('LIBPL'))
806
807py_libs = []
808for lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
809    if not lib.startswith('-l'):
810        # Python requires some special flags to link (e.g. -framework
811        # common on OS X systems), assume appending preserves order
812        main.Append(LINKFLAGS=[lib])
813    else:
814        lib = lib[2:]
815        if lib not in py_libs:
816            py_libs.append(lib)
817py_libs.append(py_version)
818
819main.Append(CPPPATH=py_includes)
820main.Append(LIBPATH=py_lib_path)
821
822# Cache build files in the supplied directory.
823if main['M5_BUILD_CACHE']:
824    print 'Using build cache located at', main['M5_BUILD_CACHE']
825    CacheDir(main['M5_BUILD_CACHE'])
826
827
828# verify that this stuff works
829if not conf.CheckHeader('Python.h', '<>'):
830    print "Error: can't find Python.h header in", py_includes
831    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
832    Exit(1)
833
834for lib in py_libs:
835    if not conf.CheckLib(lib):
836        print "Error: can't find library %s required by python" % lib
837        Exit(1)
838
839# On Solaris you need to use libsocket for socket ops
840if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
841   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
842       print "Can't find library with socket calls (e.g. accept())"
843       Exit(1)
844
845# Check for zlib.  If the check passes, libz will be automatically
846# added to the LIBS environment variable.
847if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
848    print 'Error: did not find needed zlib compression library '\
849          'and/or zlib.h header file.'
850    print '       Please install zlib and try again.'
851    Exit(1)
852
853# If we have the protobuf compiler, also make sure we have the
854# development libraries. If the check passes, libprotobuf will be
855# automatically added to the LIBS environment variable. After
856# this, we can use the HAVE_PROTOBUF flag to determine if we have
857# got both protoc and libprotobuf available.
858main['HAVE_PROTOBUF'] = main['PROTOC'] and \
859    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
860                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
861
862# If we have the compiler but not the library, print another warning.
863if main['PROTOC'] and not main['HAVE_PROTOBUF']:
864    print termcap.Yellow + termcap.Bold + \
865        'Warning: did not find protocol buffer library and/or headers.\n' + \
866    '       Please install libprotobuf-dev for tracing support.' + \
867    termcap.Normal
868
869# Check for librt.
870have_posix_clock = \
871    conf.CheckLibWithHeader(None, 'time.h', 'C',
872                            'clock_nanosleep(0,0,NULL,NULL);') or \
873    conf.CheckLibWithHeader('rt', 'time.h', 'C',
874                            'clock_nanosleep(0,0,NULL,NULL);')
875
876if conf.CheckLib('tcmalloc_minimal'):
877    have_tcmalloc = True
878else:
879    have_tcmalloc = False
880    print termcap.Yellow + termcap.Bold + \
881          "You can get a 12% performance improvement by installing tcmalloc "\
882          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
883          termcap.Normal
884
885if not have_posix_clock:
886    print "Can't find library for POSIX clocks."
887
888# Check for <fenv.h> (C99 FP environment control)
889have_fenv = conf.CheckHeader('fenv.h', '<>')
890if not have_fenv:
891    print "Warning: Header file <fenv.h> not found."
892    print "         This host has no IEEE FP rounding mode control."
893
894######################################################################
895#
896# Finish the configuration
897#
898main = conf.Finish()
899
900######################################################################
901#
902# Collect all non-global variables
903#
904
905# Define the universe of supported ISAs
906all_isa_list = [ ]
907Export('all_isa_list')
908
909class CpuModel(object):
910    '''The CpuModel class encapsulates everything the ISA parser needs to
911    know about a particular CPU model.'''
912
913    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
914    dict = {}
915    list = []
916    defaults = []
917
918    # Constructor.  Automatically adds models to CpuModel.dict.
919    def __init__(self, name, filename, includes, strings, default=False):
920        self.name = name           # name of model
921        self.filename = filename   # filename for output exec code
922        self.includes = includes   # include files needed in exec file
923        # The 'strings' dict holds all the per-CPU symbols we can
924        # substitute into templates etc.
925        self.strings = strings
926
927        # This cpu is enabled by default
928        self.default = default
929
930        # Add self to dict
931        if name in CpuModel.dict:
932            raise AttributeError, "CpuModel '%s' already registered" % name
933        CpuModel.dict[name] = self
934        CpuModel.list.append(name)
935
936Export('CpuModel')
937
938# Sticky variables get saved in the variables file so they persist from
939# one invocation to the next (unless overridden, in which case the new
940# value becomes sticky).
941sticky_vars = Variables(args=ARGUMENTS)
942Export('sticky_vars')
943
944# Sticky variables that should be exported
945export_vars = []
946Export('export_vars')
947
948# For Ruby
949all_protocols = []
950Export('all_protocols')
951protocol_dirs = []
952Export('protocol_dirs')
953slicc_includes = []
954Export('slicc_includes')
955
956# Walk the tree and execute all SConsopts scripts that wil add to the
957# above variables
958if not GetOption('verbose'):
959    print "Reading SConsopts"
960for bdir in [ base_dir ] + extras_dir_list:
961    if not isdir(bdir):
962        print "Error: directory '%s' does not exist" % bdir
963        Exit(1)
964    for root, dirs, files in os.walk(bdir):
965        if 'SConsopts' in files:
966            if GetOption('verbose'):
967                print "Reading", joinpath(root, 'SConsopts')
968            SConscript(joinpath(root, 'SConsopts'))
969
970all_isa_list.sort()
971
972sticky_vars.AddVariables(
973    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
974    ListVariable('CPU_MODELS', 'CPU models',
975                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
976                 sorted(CpuModel.list)),
977    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
978                 False),
979    BoolVariable('SS_COMPATIBLE_FP',
980                 'Make floating-point results compatible with SimpleScalar',
981                 False),
982    BoolVariable('USE_SSE2',
983                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
984                 False),
985    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
986    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
987    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
988    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
989                  all_protocols),
990    )
991
992# These variables get exported to #defines in config/*.hh (see src/SConscript).
993export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
994                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
995
996###################################################
997#
998# Define a SCons builder for configuration flag headers.
999#
1000###################################################
1001
1002# This function generates a config header file that #defines the
1003# variable symbol to the current variable setting (0 or 1).  The source
1004# operands are the name of the variable and a Value node containing the
1005# value of the variable.
1006def build_config_file(target, source, env):
1007    (variable, value) = [s.get_contents() for s in source]
1008    f = file(str(target[0]), 'w')
1009    print >> f, '#define', variable, value
1010    f.close()
1011    return None
1012
1013# Combine the two functions into a scons Action object.
1014config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1015
1016# The emitter munges the source & target node lists to reflect what
1017# we're really doing.
1018def config_emitter(target, source, env):
1019    # extract variable name from Builder arg
1020    variable = str(target[0])
1021    # True target is config header file
1022    target = joinpath('config', variable.lower() + '.hh')
1023    val = env[variable]
1024    if isinstance(val, bool):
1025        # Force value to 0/1
1026        val = int(val)
1027    elif isinstance(val, str):
1028        val = '"' + val + '"'
1029
1030    # Sources are variable name & value (packaged in SCons Value nodes)
1031    return ([target], [Value(variable), Value(val)])
1032
1033config_builder = Builder(emitter = config_emitter, action = config_action)
1034
1035main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1036
1037# libelf build is shared across all configs in the build root.
1038main.SConscript('ext/libelf/SConscript',
1039                variant_dir = joinpath(build_root, 'libelf'))
1040
1041# gzstream build is shared across all configs in the build root.
1042main.SConscript('ext/gzstream/SConscript',
1043                variant_dir = joinpath(build_root, 'gzstream'))
1044
1045# libfdt build is shared across all configs in the build root.
1046main.SConscript('ext/libfdt/SConscript',
1047                variant_dir = joinpath(build_root, 'libfdt'))
1048
1049###################################################
1050#
1051# This function is used to set up a directory with switching headers
1052#
1053###################################################
1054
1055main['ALL_ISA_LIST'] = all_isa_list
1056def make_switching_dir(dname, switch_headers, env):
1057    # Generate the header.  target[0] is the full path of the output
1058    # header to generate.  'source' is a dummy variable, since we get the
1059    # list of ISAs from env['ALL_ISA_LIST'].
1060    def gen_switch_hdr(target, source, env):
1061        fname = str(target[0])
1062        f = open(fname, 'w')
1063        isa = env['TARGET_ISA'].lower()
1064        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1065        f.close()
1066
1067    # Build SCons Action object. 'varlist' specifies env vars that this
1068    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1069    # should get re-executed.
1070    switch_hdr_action = MakeAction(gen_switch_hdr,
1071                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1072
1073    # Instantiate actions for each header
1074    for hdr in switch_headers:
1075        env.Command(hdr, [], switch_hdr_action)
1076Export('make_switching_dir')
1077
1078###################################################
1079#
1080# Define build environments for selected configurations.
1081#
1082###################################################
1083
1084for variant_path in variant_paths:
1085    print "Building in", variant_path
1086
1087    # Make a copy of the build-root environment to use for this config.
1088    env = main.Clone()
1089    env['BUILDDIR'] = variant_path
1090
1091    # variant_dir is the tail component of build path, and is used to
1092    # determine the build parameters (e.g., 'ALPHA_SE')
1093    (build_root, variant_dir) = splitpath(variant_path)
1094
1095    # Set env variables according to the build directory config.
1096    sticky_vars.files = []
1097    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1098    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1099    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1100    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1101    if isfile(current_vars_file):
1102        sticky_vars.files.append(current_vars_file)
1103        print "Using saved variables file %s" % current_vars_file
1104    else:
1105        # Build dir-specific variables file doesn't exist.
1106
1107        # Make sure the directory is there so we can create it later
1108        opt_dir = dirname(current_vars_file)
1109        if not isdir(opt_dir):
1110            mkdir(opt_dir)
1111
1112        # Get default build variables from source tree.  Variables are
1113        # normally determined by name of $VARIANT_DIR, but can be
1114        # overridden by '--default=' arg on command line.
1115        default = GetOption('default')
1116        opts_dir = joinpath(main.root.abspath, 'build_opts')
1117        if default:
1118            default_vars_files = [joinpath(build_root, 'variables', default),
1119                                  joinpath(opts_dir, default)]
1120        else:
1121            default_vars_files = [joinpath(opts_dir, variant_dir)]
1122        existing_files = filter(isfile, default_vars_files)
1123        if existing_files:
1124            default_vars_file = existing_files[0]
1125            sticky_vars.files.append(default_vars_file)
1126            print "Variables file %s not found,\n  using defaults in %s" \
1127                  % (current_vars_file, default_vars_file)
1128        else:
1129            print "Error: cannot find variables file %s or " \
1130                  "default file(s) %s" \
1131                  % (current_vars_file, ' or '.join(default_vars_files))
1132            Exit(1)
1133
1134    # Apply current variable settings to env
1135    sticky_vars.Update(env)
1136
1137    help_texts["local_vars"] += \
1138        "Build variables for %s:\n" % variant_dir \
1139                 + sticky_vars.GenerateHelpText(env)
1140
1141    # Process variable settings.
1142
1143    if not have_fenv and env['USE_FENV']:
1144        print "Warning: <fenv.h> not available; " \
1145              "forcing USE_FENV to False in", variant_dir + "."
1146        env['USE_FENV'] = False
1147
1148    if not env['USE_FENV']:
1149        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1150        print "         FP results may deviate slightly from other platforms."
1151
1152    if env['EFENCE']:
1153        env.Append(LIBS=['efence'])
1154
1155    # Save sticky variable settings back to current variables file
1156    sticky_vars.Save(current_vars_file, env)
1157
1158    if env['USE_SSE2']:
1159        env.Append(CCFLAGS=['-msse2'])
1160
1161    if have_tcmalloc:
1162        env.Append(LIBS=['tcmalloc_minimal'])
1163
1164    # The src/SConscript file sets up the build rules in 'env' according
1165    # to the configured variables.  It returns a list of environments,
1166    # one for each variant build (debug, opt, etc.)
1167    envList = SConscript('src/SConscript', variant_dir = variant_path,
1168                         exports = 'env')
1169
1170    # Set up the regression tests for each build.
1171    for e in envList:
1172        SConscript('tests/SConscript',
1173                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1174                   exports = { 'env' : e }, duplicate = False)
1175
1176# base help text
1177Help('''
1178Usage: scons [scons options] [build variables] [target(s)]
1179
1180Extra scons options:
1181%(options)s
1182
1183Global build variables:
1184%(global_vars)s
1185
1186%(local_vars)s
1187''' % help_texts)
1188