SConstruct revision 8878
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
4955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
5955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
6955SN/A# All rights reserved.
7955SN/A#
8955SN/A# Redistribution and use in source and binary forms, with or without
9955SN/A# modification, are permitted provided that the following conditions are
10955SN/A# met: redistributions of source code must retain the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer;
12955SN/A# redistributions in binary form must reproduce the above copyright
13955SN/A# notice, this list of conditions and the following disclaimer in the
14955SN/A# documentation and/or other materials provided with the distribution;
15955SN/A# neither the name of the copyright holders nor the names of its
16955SN/A# contributors may be used to endorse or promote products derived from
17955SN/A# this software without specific prior written permission.
18955SN/A#
19955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
282665Ssaidi@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
292665Ssaidi@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30955SN/A#
31955SN/A# Authors: Steve Reinhardt
32955SN/A#          Nathan Binkert
33955SN/A
34955SN/A###################################################
352632Sstever@eecs.umich.edu#
362632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
372632Sstever@eecs.umich.edu#
382632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
39955SN/A# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
402632Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
412632Sstever@eecs.umich.edu# the optimized full-system version).
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
442632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
452632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
462761Sstever@eecs.umich.edu# built for the same host system.
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# Examples:
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
512761Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
522761Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
532761Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
562632Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
572632Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
582632Sstever@eecs.umich.edu#   file.
592632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
602632Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
63955SN/A# 'gem5' directory (or use -u or -C to tell scons where to find this
64955SN/A# file), you can use 'scons -h' to print all the gem5-specific build
65955SN/A# options as well.
66955SN/A#
67955SN/A###################################################
68955SN/A
693716Sstever@eecs.umich.edu# Check for recent-enough Python and SCons versions.
70955SN/Atry:
712656Sstever@eecs.umich.edu    # Really old versions of scons only take two options for the
722656Sstever@eecs.umich.edu    # function, so check once without the revision and once with the
732656Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
742656Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
752656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
762656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
772656Sstever@eecs.umich.eduexcept SystemExit, e:
782653Sstever@eecs.umich.edu    print """
792653Sstever@eecs.umich.eduFor more details, see:
802653Sstever@eecs.umich.edu    http://gem5.org/Dependencies
812653Sstever@eecs.umich.edu"""
822653Sstever@eecs.umich.edu    raise
832653Sstever@eecs.umich.edu
842653Sstever@eecs.umich.edu# We ensure the python version early because we have stuff that
852653Sstever@eecs.umich.edu# requires python 2.4
862653Sstever@eecs.umich.edutry:
872653Sstever@eecs.umich.edu    EnsurePythonVersion(2, 4)
882653Sstever@eecs.umich.eduexcept SystemExit, e:
891852SN/A    print """
90955SN/AYou can use a non-default installation of the Python interpreter by
91955SN/Aeither (1) rearranging your PATH so that scons finds the non-default
92955SN/A'python' first or (2) explicitly invoking an alternative interpreter
933717Sstever@eecs.umich.eduon the scons script.
943716Sstever@eecs.umich.edu
95955SN/AFor more details, see:
961533SN/A    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
973716Sstever@eecs.umich.edu"""
981533SN/A    raise
99955SN/A
100955SN/A# Global Python includes
1012632Sstever@eecs.umich.eduimport os
1022632Sstever@eecs.umich.eduimport re
103955SN/Aimport subprocess
104955SN/Aimport sys
105955SN/A
106955SN/Afrom os import mkdir, environ
1072632Sstever@eecs.umich.edufrom os.path import abspath, basename, dirname, expanduser, normpath
108955SN/Afrom os.path import exists,  isdir, isfile
1092632Sstever@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
1102632Sstever@eecs.umich.edu
1112632Sstever@eecs.umich.edu# SCons includes
1122632Sstever@eecs.umich.eduimport SCons
1132632Sstever@eecs.umich.eduimport SCons.Node
1142632Sstever@eecs.umich.edu
1152632Sstever@eecs.umich.eduextra_python_paths = [
1163053Sstever@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1173053Sstever@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1183053Sstever@eecs.umich.edu    ]
1193053Sstever@eecs.umich.edu    
1203053Sstever@eecs.umich.edusys.path[1:1] = extra_python_paths
1213053Sstever@eecs.umich.edu
1223053Sstever@eecs.umich.edufrom m5.util import compareVersions, readCommand
1233053Sstever@eecs.umich.edu
1243053Sstever@eecs.umich.eduhelp_texts = {
1253053Sstever@eecs.umich.edu    "options" : "",
1263053Sstever@eecs.umich.edu    "global_vars" : "",
1273053Sstever@eecs.umich.edu    "local_vars" : ""
1283053Sstever@eecs.umich.edu}
1293053Sstever@eecs.umich.edu
1303053Sstever@eecs.umich.eduExport("help_texts")
1313053Sstever@eecs.umich.edu
1322632Sstever@eecs.umich.edudef AddM5Option(*args, **kwargs):
1332632Sstever@eecs.umich.edu    col_width = 30
1342632Sstever@eecs.umich.edu
1352632Sstever@eecs.umich.edu    help = "  " + ", ".join(args)
1362632Sstever@eecs.umich.edu    if "help" in kwargs:
1372632Sstever@eecs.umich.edu        length = len(help)
1383718Sstever@eecs.umich.edu        if length >= col_width:
1393718Sstever@eecs.umich.edu            help += "\n" + " " * col_width
1403718Sstever@eecs.umich.edu        else:
1413718Sstever@eecs.umich.edu            help += " " * (col_width - length)
1423718Sstever@eecs.umich.edu        help += kwargs["help"]
1433718Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
1443718Sstever@eecs.umich.edu
1453718Sstever@eecs.umich.edu    AddOption(*args, **kwargs)
1463718Sstever@eecs.umich.edu
1473718Sstever@eecs.umich.eduAddM5Option('--colors', dest='use_colors', action='store_true',
1483718Sstever@eecs.umich.edu            help="Add color to abbreviated scons output")
1493718Sstever@eecs.umich.eduAddM5Option('--no-colors', dest='use_colors', action='store_false',
1503718Sstever@eecs.umich.edu            help="Don't add color to abbreviated scons output")
1512634Sstever@eecs.umich.eduAddM5Option('--default', dest='default', type='string', action='store',
1522634Sstever@eecs.umich.edu            help='Override which build_opts file to use for defaults')
1532632Sstever@eecs.umich.eduAddM5Option('--ignore-style', dest='ignore_style', action='store_true',
1542638Sstever@eecs.umich.edu            help='Disable style checking hooks')
1552632Sstever@eecs.umich.eduAddM5Option('--update-ref', dest='update_ref', action='store_true',
1562632Sstever@eecs.umich.edu            help='Update test reference outputs')
1572632Sstever@eecs.umich.eduAddM5Option('--verbose', dest='verbose', action='store_true',
1582632Sstever@eecs.umich.edu            help='Print full tool command lines')
1592632Sstever@eecs.umich.edu
1602632Sstever@eecs.umich.eduuse_colors = GetOption('use_colors')
1611858SN/Aif use_colors:
1623716Sstever@eecs.umich.edu    from m5.util.terminal import termcap
1632638Sstever@eecs.umich.eduelif use_colors is None:
1642638Sstever@eecs.umich.edu    # option unspecified; default behavior is to use colors iff isatty
1652638Sstever@eecs.umich.edu    from m5.util.terminal import tty_termcap as termcap
1662638Sstever@eecs.umich.eduelse:
1672638Sstever@eecs.umich.edu    from m5.util.terminal import no_termcap as termcap
1682638Sstever@eecs.umich.edu
1692638Sstever@eecs.umich.edu########################################################################
1703716Sstever@eecs.umich.edu#
1712634Sstever@eecs.umich.edu# Set up the main build environment.
1722634Sstever@eecs.umich.edu#
173955SN/A########################################################################
174955SN/Ause_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
175955SN/A                 'PYTHONPATH', 'RANLIB' ])
176955SN/A
177955SN/Ause_env = {}
178955SN/Afor key,val in os.environ.iteritems():
179955SN/A    if key in use_vars or key.startswith("M5"):
180955SN/A        use_env[key] = val
1811858SN/A
1821858SN/Amain = Environment(ENV=use_env)
1832632Sstever@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
184955SN/Amain.srcdir = Dir("src")     # The source directory
1853643Ssaidi@eecs.umich.edu
1863643Ssaidi@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
1873643Ssaidi@eecs.umich.edu# as well
1883643Ssaidi@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
1893643Ssaidi@eecs.umich.edu
1903643Ssaidi@eecs.umich.edu########################################################################
1913643Ssaidi@eecs.umich.edu#
1923643Ssaidi@eecs.umich.edu# Mercurial Stuff.
1933716Sstever@eecs.umich.edu#
1941105SN/A# If the gem5 directory is a mercurial repository, we should do some
1952667Sstever@eecs.umich.edu# extra things.
1962667Sstever@eecs.umich.edu#
1972667Sstever@eecs.umich.edu########################################################################
1982667Sstever@eecs.umich.edu
1992667Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2002667Sstever@eecs.umich.edu
2011869SN/Amercurial_style_message = """
2021869SN/AYou're missing the gem5 style hook, which automatically checks your code
2031869SN/Aagainst the gem5 style rules on hg commit and qrefresh commands.  This
2041869SN/Ascript will now install the hook in your .hg/hgrc file.
2051869SN/APress enter to continue, or ctrl-c to abort: """
2061065SN/A
2072632Sstever@eecs.umich.edumercurial_style_hook = """
2082632Sstever@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
209955SN/A# to provide the gem5 style-checking hooks
2101858SN/A[extensions]
2111858SN/Astyle = %s/util/style.py
2121858SN/A
2131858SN/A[hooks]
2141851SN/Apretxncommit.style = python:style.check_style
2151851SN/Apre-qrefresh.style = python:style.check_style
2161858SN/A# End of SConstruct additions
2172632Sstever@eecs.umich.edu
218955SN/A""" % (main.root.abspath)
2193053Sstever@eecs.umich.edu
2203053Sstever@eecs.umich.edumercurial_lib_not_found = """
2213053Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook.  If
2223053Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
2233053Sstever@eecs.umich.eduhook. It is important.
2243053Sstever@eecs.umich.edu"""
2253053Sstever@eecs.umich.edu
2263053Sstever@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
2273053Sstever@eecs.umich.edu# Skip this if --ignore-style was specified, there's no .hg dir to
2283053Sstever@eecs.umich.edu# install a hook in, or there's no interactive terminal to prompt.
2293053Sstever@eecs.umich.eduif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2303053Sstever@eecs.umich.edu    style_hook = True
2313053Sstever@eecs.umich.edu    try:
2323053Sstever@eecs.umich.edu        from mercurial import ui
2333053Sstever@eecs.umich.edu        ui = ui.ui()
2343053Sstever@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2353053Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2363053Sstever@eecs.umich.edu                     ui.config('hooks', 'pre-qrefresh.style', None)
2373053Sstever@eecs.umich.edu    except ImportError:
2382667Sstever@eecs.umich.edu        print mercurial_lib_not_found
2392667Sstever@eecs.umich.edu
2402667Sstever@eecs.umich.edu    if not style_hook:
2412667Sstever@eecs.umich.edu        print mercurial_style_message,
2422667Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
2432667Sstever@eecs.umich.edu        try:
2442667Sstever@eecs.umich.edu            raw_input()
2452667Sstever@eecs.umich.edu        except:
2462667Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
2472667Sstever@eecs.umich.edu            sys.exit(1)
2482667Sstever@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2492667Sstever@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
2502638Sstever@eecs.umich.edu        try:
2512638Sstever@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
2522638Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
2533716Sstever@eecs.umich.edu            hgrc.close()
2543716Sstever@eecs.umich.edu        except:
2551858SN/A            print "Error updating", hgrc_path
2563118Sstever@eecs.umich.edu            sys.exit(1)
2573118Sstever@eecs.umich.edu
2583118Sstever@eecs.umich.edu
2593118Sstever@eecs.umich.edu###################################################
2603118Sstever@eecs.umich.edu#
2613118Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
2623118Sstever@eecs.umich.edu# the target(s).
2633118Sstever@eecs.umich.edu#
2643118Sstever@eecs.umich.edu###################################################
2653118Sstever@eecs.umich.edu
2663118Sstever@eecs.umich.edu# Find default configuration & binary.
2673716Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2683118Sstever@eecs.umich.edu
2693118Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2703118Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2713118Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2723118Sstever@eecs.umich.edu        if l[i] == elt:
2733118Sstever@eecs.umich.edu            return i
2743118Sstever@eecs.umich.edu    raise ValueError, "element not found"
2753118Sstever@eecs.umich.edu
2763118Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
2773716Sstever@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
2783118Sstever@eecs.umich.edu# relative to the launch directory unless a different root is provided
2793118Sstever@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
2803118Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
2813118Sstever@eecs.umich.edu            for p in path_list]
2823118Sstever@eecs.umich.edu
2833118Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2843118Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2853118Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2863118Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2873118Sstever@eecs.umich.edu# follow 'build' in the build path.
2883483Ssaidi@eecs.umich.edu
2893494Ssaidi@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
2903494Ssaidi@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
2913483Ssaidi@eecs.umich.edu# doesn't work (obviously!).
2923483Ssaidi@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2933483Ssaidi@eecs.umich.edu
2943053Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2953053Sstever@eecs.umich.edu# collected targets reference.
2963053Sstever@eecs.umich.eduvariant_paths = []
2973053Sstever@eecs.umich.edubuild_root = None
2983053Sstever@eecs.umich.edufor t in BUILD_TARGETS:
2993053Sstever@eecs.umich.edu    path_dirs = t.split('/')
3003053Sstever@eecs.umich.edu    try:
3013053Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3021858SN/A    except:
3031858SN/A        print "Error: no non-leaf 'build' dir found on target path", t
3041858SN/A        Exit(1)
3051858SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3061858SN/A    if not build_root:
3071858SN/A        build_root = this_build_root
3081859SN/A    else:
3091858SN/A        if this_build_root != build_root:
3101858SN/A            print "Error: build targets not under same build root\n"\
3111858SN/A                  "  %s\n  %s" % (build_root, this_build_root)
3121859SN/A            Exit(1)
3131859SN/A    variant_path = joinpath('/',*path_dirs[:build_top+2])
3141862SN/A    if variant_path not in variant_paths:
3153053Sstever@eecs.umich.edu        variant_paths.append(variant_path)
3163053Sstever@eecs.umich.edu
3173053Sstever@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
3183053Sstever@eecs.umich.eduif not isdir(build_root):
3191859SN/A    mkdir(build_root)
3201859SN/Amain['BUILDROOT'] = build_root
3211859SN/A
3221859SN/AExport('main')
3231859SN/A
3241859SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
3251859SN/A
3261859SN/A# Default duplicate option is to use hard links, but this messes up
3271862SN/A# when you use emacs to edit a file in the target dir, as emacs moves
3281859SN/A# file to file~ then copies to file, breaking the link.  Symbolic
3291859SN/A# (soft) links work better.
3301859SN/Amain.SetOption('duplicate', 'soft-copy')
3311858SN/A
3321858SN/A#
3332139SN/A# Set up global sticky variables... these are common to an entire build
3342139SN/A# tree (not specific to a particular build like ALPHA_SE)
3352139SN/A#
3362155SN/A
3372623SN/Aglobal_vars_file = joinpath(build_root, 'variables.global')
3383583Sbinkertn@umich.edu
3393583Sbinkertn@umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3403717Sstever@eecs.umich.edu
3413583Sbinkertn@umich.eduglobal_vars.AddVariables(
3422155SN/A    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3431869SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3441869SN/A    ('BATCH', 'Use batch pool for build and tests', False),
3451869SN/A    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3461869SN/A    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3471869SN/A    ('EXTRAS', 'Add extra directories to the compilation', '')
3482139SN/A    )
3491869SN/A
3502508SN/A# Update main environment with values from ARGUMENTS & global_vars_file
3512508SN/Aglobal_vars.Update(main)
3522508SN/Ahelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3532508SN/A
3543685Sktlim@umich.edu# Save sticky variable settings back to current variables file
3552635Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
3561869SN/A
3571869SN/A# Parse EXTRAS variable to build list of all directories where we're
3581869SN/A# look for sources etc.  This list is exported as extras_dir_list.
3591869SN/Abase_dir = main.srcdir.abspath
3601869SN/Aif main['EXTRAS']:
3611869SN/A    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3621869SN/Aelse:
3631869SN/A    extras_dir_list = []
3641965SN/A
3651965SN/AExport('base_dir')
3661965SN/AExport('extras_dir_list')
3671869SN/A
3681869SN/A# the ext directory should be on the #includes path
3692733Sktlim@umich.edumain.Append(CPPPATH=[Dir('ext')])
3701869SN/A
3711884SN/Adef strip_build_path(path, env):
3721884SN/A    path = str(path)
3733356Sbinkertn@umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
3743356Sbinkertn@umich.edu    if path.startswith(variant_base):
3753356Sbinkertn@umich.edu        path = path[len(variant_base):]
3763356Sbinkertn@umich.edu    elif path.startswith('build/'):
3771869SN/A        path = path[6:]
3781858SN/A    return path
3791869SN/A
3801869SN/A# Generate a string of the form:
3811869SN/A#   common/path/prefix/src1, src2 -> tgt1, tgt2
3821869SN/A# to print while building.
3831869SN/Aclass Transform(object):
3841858SN/A    # all specific color settings should be here and nowhere else
3852761Sstever@eecs.umich.edu    tool_color = termcap.Normal
3861869SN/A    pfx_color = termcap.Yellow
3872733Sktlim@umich.edu    srcs_color = termcap.Yellow + termcap.Bold
3883584Ssaidi@eecs.umich.edu    arrow_color = termcap.Blue + termcap.Bold
3891869SN/A    tgts_color = termcap.Yellow + termcap.Bold
3901869SN/A
3911869SN/A    def __init__(self, tool, max_sources=99):
3921869SN/A        self.format = self.tool_color + (" [%8s] " % tool) \
3931869SN/A                      + self.pfx_color + "%s" \
3941869SN/A                      + self.srcs_color + "%s" \
3951858SN/A                      + self.arrow_color + " -> " \
396955SN/A                      + self.tgts_color + "%s" \
397955SN/A                      + termcap.Normal
3981869SN/A        self.max_sources = max_sources
3991869SN/A
4001869SN/A    def __call__(self, target, source, env, for_signature=None):
4011869SN/A        # truncate source list according to max_sources param
4021869SN/A        source = source[0:self.max_sources]
4031869SN/A        def strip(f):
4041869SN/A            return strip_build_path(str(f), env)
4051869SN/A        if len(source) > 0:
4061869SN/A            srcs = map(strip, source)
4071869SN/A        else:
4081869SN/A            srcs = ['']
4091869SN/A        tgts = map(strip, target)
4101869SN/A        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4111869SN/A        # operation that has nothing to do with paths.
4121869SN/A        com_pfx = os.path.commonprefix(srcs + tgts)
4131869SN/A        com_pfx_len = len(com_pfx)
4141869SN/A        if com_pfx:
4151869SN/A            # do some cleanup and sanity checking on common prefix
4161869SN/A            if com_pfx[-1] == ".":
4171869SN/A                # prefix matches all but file extension: ok
4181869SN/A                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4191869SN/A                com_pfx = com_pfx[0:-1]
4201869SN/A            elif com_pfx[-1] == "/":
4211869SN/A                # common prefix is directory path: OK
4221869SN/A                pass
4231869SN/A            else:
4241869SN/A                src0_len = len(srcs[0])
4251869SN/A                tgt0_len = len(tgts[0])
4261869SN/A                if src0_len == com_pfx_len:
4273716Sstever@eecs.umich.edu                    # source is a substring of target, OK
4283356Sbinkertn@umich.edu                    pass
4293356Sbinkertn@umich.edu                elif tgt0_len == com_pfx_len:
4303356Sbinkertn@umich.edu                    # target is a substring of source, need to back up to
4313356Sbinkertn@umich.edu                    # avoid empty string on RHS of arrow
4323356Sbinkertn@umich.edu                    sep_idx = com_pfx.rfind(".")
4333356Sbinkertn@umich.edu                    if sep_idx != -1:
4343356Sbinkertn@umich.edu                        com_pfx = com_pfx[0:sep_idx]
4351869SN/A                    else:
4361869SN/A                        com_pfx = ''
4371869SN/A                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4381869SN/A                    # still splitting at file extension: ok
4391869SN/A                    pass
4401869SN/A                else:
4411869SN/A                    # probably a fluke; ignore it
4422655Sstever@eecs.umich.edu                    com_pfx = ''
4432655Sstever@eecs.umich.edu        # recalculate length in case com_pfx was modified
4442655Sstever@eecs.umich.edu        com_pfx_len = len(com_pfx)
4452655Sstever@eecs.umich.edu        def fmt(files):
4462655Sstever@eecs.umich.edu            f = map(lambda s: s[com_pfx_len:], files)
4472655Sstever@eecs.umich.edu            return ', '.join(f)
4482655Sstever@eecs.umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4492655Sstever@eecs.umich.edu
4502655Sstever@eecs.umich.eduExport('Transform')
4512655Sstever@eecs.umich.edu
4522655Sstever@eecs.umich.edu
4532655Sstever@eecs.umich.eduif GetOption('verbose'):
4542655Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
4552655Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
4562655Sstever@eecs.umich.eduelse:
4572655Sstever@eecs.umich.edu    MakeAction = Action
4582655Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
4592655Sstever@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
4602655Sstever@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
4612655Sstever@eecs.umich.edu    main['SWIGCOMSTR']      = Transform("SWIG")
4622655Sstever@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
4632655Sstever@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
4642655Sstever@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4652655Sstever@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
4662655Sstever@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
4672655Sstever@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
4682634Sstever@eecs.umich.eduExport('MakeAction')
4692634Sstever@eecs.umich.edu
4702634Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
4712634Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
4722634Sstever@eecs.umich.edu
4732634Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
4742638Sstever@eecs.umich.edumain['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
4752638Sstever@eecs.umich.edumain['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
4763716Sstever@eecs.umich.edumain['CLANG'] = CXX_V and CXX_V.find('clang') >= 0
4772638Sstever@eecs.umich.eduif main['GCC'] + main['SUNCC'] + main['ICC'] + main['CLANG'] > 1:
4782638Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
4791869SN/A    Exit(1)
4801869SN/A
4813546Sgblack@eecs.umich.edu# Set up default C++ compiler flags
4823546Sgblack@eecs.umich.eduif main['GCC']:
4833546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
4843546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
4853546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
4863546Sgblack@eecs.umich.edu    main.Append(CXXFLAGS=['-Wno-deprecated'])
4873546Sgblack@eecs.umich.edu    # Read the GCC version to check for versions with bugs
4883546Sgblack@eecs.umich.edu    # Note CCVERSION doesn't work here because it is run with the CC
4893546Sgblack@eecs.umich.edu    # before we override it from the command line
4903546Sgblack@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
4913546Sgblack@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
4923546Sgblack@eecs.umich.edu    if not compareVersions(gcc_version, '4.4.1') or \
4933546Sgblack@eecs.umich.edu       not compareVersions(gcc_version, '4.4.2'):
4943546Sgblack@eecs.umich.edu        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
4953546Sgblack@eecs.umich.edu        main.Append(CCFLAGS=['-fno-tree-vectorize'])
4963546Sgblack@eecs.umich.eduelif main['ICC']:
4973546Sgblack@eecs.umich.edu    pass #Fix me... add warning flags once we clean up icc warnings
4983546Sgblack@eecs.umich.eduelif main['SUNCC']:
4993546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Qoption ccfe'])
5003546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-features=gcc'])
5013546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-features=extensions'])
5023546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-library=stlport4'])
5033546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-xar'])
5043546Sgblack@eecs.umich.edu    #main.Append(CCFLAGS=['-instances=semiexplicit'])
5053546Sgblack@eecs.umich.eduelif main['CLANG']:
5063546Sgblack@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
5073546Sgblack@eecs.umich.edu    clang_version_match = clang_version_re.match(CXX_version)
5083546Sgblack@eecs.umich.edu    if (clang_version_match):
5093546Sgblack@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
5103546Sgblack@eecs.umich.edu        if compareVersions(clang_version, "2.9") < 0:
5113546Sgblack@eecs.umich.edu            print 'Error: clang version 2.9 or newer required.'
5123546Sgblack@eecs.umich.edu            print '       Installed version:', clang_version
5133546Sgblack@eecs.umich.edu            Exit(1)
5143546Sgblack@eecs.umich.edu    else:
5153546Sgblack@eecs.umich.edu        print 'Error: Unable to determine clang version.'
5163546Sgblack@eecs.umich.edu        Exit(1)
5173546Sgblack@eecs.umich.edu
5183546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
5193546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5203546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
521955SN/A    main.Append(CCFLAGS=['-Wno-tautological-compare'])
522955SN/A    main.Append(CCFLAGS=['-Wno-self-assign'])
523955SN/Aelse:
524955SN/A    print 'Error: Don\'t know what compiler options to use for your compiler.'
5251858SN/A    print '       Please fix SConstruct and src/SConscript and try again.'
5261858SN/A    Exit(1)
5271858SN/A
5282632Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
5292632Sstever@eecs.umich.edumain['YACCFLAGS'] = '-d'
5302632Sstever@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5312632Sstever@eecs.umich.edu
5322632Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
5332634Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
5342638Sstever@eecs.umich.eduif main['BATCH']:
5352023SN/A    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5362632Sstever@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5372632Sstever@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5382632Sstever@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5392632Sstever@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5402632Sstever@eecs.umich.edu
5413716Sstever@eecs.umich.eduif sys.platform == 'cygwin':
5422632Sstever@eecs.umich.edu    # cygwin has some header file issues...
5432632Sstever@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
5442632Sstever@eecs.umich.edu
5452632Sstever@eecs.umich.edu# Check for SWIG
5462632Sstever@eecs.umich.eduif not main.has_key('SWIG'):
5472023SN/A    print 'Error: SWIG utility not found.'
5482632Sstever@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
5492632Sstever@eecs.umich.edu    Exit(1)
5501889SN/A
5511889SN/A# Check for appropriate SWIG version
5522632Sstever@eecs.umich.eduswig_version = readCommand(('swig', '-version'), exception='').split()
5532632Sstever@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
5542632Sstever@eecs.umich.eduif len(swig_version) < 3 or \
5552632Sstever@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
5563716Sstever@eecs.umich.edu    print 'Error determining SWIG version.'
5573716Sstever@eecs.umich.edu    Exit(1)
5582632Sstever@eecs.umich.edu
5592632Sstever@eecs.umich.edumin_swig_version = '1.3.28'
5602632Sstever@eecs.umich.eduif compareVersions(swig_version[2], min_swig_version) < 0:
5612632Sstever@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
5622632Sstever@eecs.umich.edu    print '       Installed version:', swig_version[2]
5632632Sstever@eecs.umich.edu    Exit(1)
5642632Sstever@eecs.umich.edu
5652632Sstever@eecs.umich.edu# Set up SWIG flags & scanner
5661888SN/Aswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
5671888SN/Amain.Append(SWIGFLAGS=swig_flags)
5681869SN/A
5691869SN/A# filter out all existing swig scanners, they mess up the dependency
5701858SN/A# stuff for some reason
5712598SN/Ascanners = []
5722598SN/Afor scanner in main['SCANNERS']:
5732598SN/A    skeys = scanner.skeys
5742598SN/A    if skeys == '.i':
5752598SN/A        continue
5761858SN/A
5771858SN/A    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
5781858SN/A        continue
5791858SN/A
5801858SN/A    scanners.append(scanner)
5811858SN/A
5821858SN/A# add the new swig scanner that we like better
5831858SN/Afrom SCons.Scanner import ClassicCPP as CPPScanner
5841858SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
5851871SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
5861858SN/A
5871858SN/A# replace the scanners list that has what we want
5881858SN/Amain['SCANNERS'] = scanners
5891858SN/A
5901858SN/A# Add a custom Check function to the Configure context so that we can
5911858SN/A# figure out if the compiler adds leading underscores to global
5921858SN/A# variables.  This is needed for the autogenerated asm files that we
5931858SN/A# use for embedding the python code.
5941858SN/Adef CheckLeading(context):
5951858SN/A    context.Message("Checking for leading underscore in global variables...")
5961858SN/A    # 1) Define a global variable called x from asm so the C compiler
5971859SN/A    #    won't change the symbol at all.
5981859SN/A    # 2) Declare that variable.
5991869SN/A    # 3) Use the variable
6001888SN/A    #
6012632Sstever@eecs.umich.edu    # If the compiler prepends an underscore, this will successfully
6021869SN/A    # link because the external symbol 'x' will be called '_x' which
6031884SN/A    # was defined by the asm statement.  If the compiler does not
6041884SN/A    # prepend an underscore, this will not successfully link because
6051884SN/A    # '_x' will have been defined by assembly, while the C portion of
6061884SN/A    # the code will be trying to use 'x'
6071884SN/A    ret = context.TryLink('''
6081884SN/A        asm(".globl _x; _x: .byte 0");
6091965SN/A        extern int x;
6101965SN/A        int main() { return x; }
6111965SN/A        ''', extension=".c")
6122761Sstever@eecs.umich.edu    context.env.Append(LEADING_UNDERSCORE=ret)
6131869SN/A    context.Result(ret)
6141869SN/A    return ret
6152632Sstever@eecs.umich.edu
6162667Sstever@eecs.umich.edu# Platform-specific configuration.  Note again that we assume that all
6171869SN/A# builds under a given build root run on the same host platform.
6181869SN/Aconf = Configure(main,
6192929Sktlim@umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
6202929Sktlim@umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
6213716Sstever@eecs.umich.edu                 custom_tests = { 'CheckLeading' : CheckLeading })
6222929Sktlim@umich.edu
623955SN/A# Check for leading underscores.  Don't really need to worry either
6242598SN/A# way so don't need to check the return code.
6252598SN/Aconf.CheckLeading()
6263546Sgblack@eecs.umich.edu
627955SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
628955SN/Atry:
629955SN/A    import platform
6301530SN/A    uname = platform.uname()
631955SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
632955SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
633955SN/A            main.Append(CCFLAGS=['-arch', 'x86_64'])
634            main.Append(CFLAGS=['-arch', 'x86_64'])
635            main.Append(LINKFLAGS=['-arch', 'x86_64'])
636            main.Append(ASFLAGS=['-arch', 'x86_64'])
637except:
638    pass
639
640# Recent versions of scons substitute a "Null" object for Configure()
641# when configuration isn't necessary, e.g., if the "--help" option is
642# present.  Unfortuantely this Null object always returns false,
643# breaking all our configuration checks.  We replace it with our own
644# more optimistic null object that returns True instead.
645if not conf:
646    def NullCheck(*args, **kwargs):
647        return True
648
649    class NullConf:
650        def __init__(self, env):
651            self.env = env
652        def Finish(self):
653            return self.env
654        def __getattr__(self, mname):
655            return NullCheck
656
657    conf = NullConf(main)
658
659# Find Python include and library directories for embedding the
660# interpreter.  For consistency, we will use the same Python
661# installation used to run scons (and thus this script).  If you want
662# to link in an alternate version, see above for instructions on how
663# to invoke scons with a different copy of the Python interpreter.
664from distutils import sysconfig
665
666py_getvar = sysconfig.get_config_var
667
668py_debug = getattr(sys, 'pydebug', False)
669py_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
670
671py_general_include = sysconfig.get_python_inc()
672py_platform_include = sysconfig.get_python_inc(plat_specific=True)
673py_includes = [ py_general_include ]
674if py_platform_include != py_general_include:
675    py_includes.append(py_platform_include)
676
677py_lib_path = [ py_getvar('LIBDIR') ]
678# add the prefix/lib/pythonX.Y/config dir, but only if there is no
679# shared library in prefix/lib/.
680if not py_getvar('Py_ENABLE_SHARED'):
681    py_lib_path.append(py_getvar('LIBPL'))
682
683py_libs = []
684for lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
685    if not lib.startswith('-l'):
686        # Python requires some special flags to link (e.g. -framework
687        # common on OS X systems), assume appending preserves order
688        main.Append(LINKFLAGS=[lib])
689    else:
690        lib = lib[2:]
691        if lib not in py_libs:
692            py_libs.append(lib)
693py_libs.append(py_version)
694
695main.Append(CPPPATH=py_includes)
696main.Append(LIBPATH=py_lib_path)
697
698# Cache build files in the supplied directory.
699if main['M5_BUILD_CACHE']:
700    print 'Using build cache located at', main['M5_BUILD_CACHE']
701    CacheDir(main['M5_BUILD_CACHE'])
702
703
704# verify that this stuff works
705if not conf.CheckHeader('Python.h', '<>'):
706    print "Error: can't find Python.h header in", py_includes
707    Exit(1)
708
709for lib in py_libs:
710    if not conf.CheckLib(lib):
711        print "Error: can't find library %s required by python" % lib
712        Exit(1)
713
714# On Solaris you need to use libsocket for socket ops
715if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
716   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
717       print "Can't find library with socket calls (e.g. accept())"
718       Exit(1)
719
720# Check for zlib.  If the check passes, libz will be automatically
721# added to the LIBS environment variable.
722if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
723    print 'Error: did not find needed zlib compression library '\
724          'and/or zlib.h header file.'
725    print '       Please install zlib and try again.'
726    Exit(1)
727
728# Check for librt.
729have_posix_clock = \
730    conf.CheckLibWithHeader(None, 'time.h', 'C',
731                            'clock_nanosleep(0,0,NULL,NULL);') or \
732    conf.CheckLibWithHeader('rt', 'time.h', 'C',
733                            'clock_nanosleep(0,0,NULL,NULL);')
734
735if not have_posix_clock:
736    print "Can't find library for POSIX clocks."
737
738# Check for <fenv.h> (C99 FP environment control)
739have_fenv = conf.CheckHeader('fenv.h', '<>')
740if not have_fenv:
741    print "Warning: Header file <fenv.h> not found."
742    print "         This host has no IEEE FP rounding mode control."
743
744######################################################################
745#
746# Finish the configuration
747#
748main = conf.Finish()
749
750######################################################################
751#
752# Collect all non-global variables
753#
754
755# Define the universe of supported ISAs
756all_isa_list = [ ]
757Export('all_isa_list')
758
759class CpuModel(object):
760    '''The CpuModel class encapsulates everything the ISA parser needs to
761    know about a particular CPU model.'''
762
763    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
764    dict = {}
765    list = []
766    defaults = []
767
768    # Constructor.  Automatically adds models to CpuModel.dict.
769    def __init__(self, name, filename, includes, strings, default=False):
770        self.name = name           # name of model
771        self.filename = filename   # filename for output exec code
772        self.includes = includes   # include files needed in exec file
773        # The 'strings' dict holds all the per-CPU symbols we can
774        # substitute into templates etc.
775        self.strings = strings
776
777        # This cpu is enabled by default
778        self.default = default
779
780        # Add self to dict
781        if name in CpuModel.dict:
782            raise AttributeError, "CpuModel '%s' already registered" % name
783        CpuModel.dict[name] = self
784        CpuModel.list.append(name)
785
786Export('CpuModel')
787
788# Sticky variables get saved in the variables file so they persist from
789# one invocation to the next (unless overridden, in which case the new
790# value becomes sticky).
791sticky_vars = Variables(args=ARGUMENTS)
792Export('sticky_vars')
793
794# Sticky variables that should be exported
795export_vars = []
796Export('export_vars')
797
798# Walk the tree and execute all SConsopts scripts that wil add to the
799# above variables
800if not GetOption('verbose'):
801    print "Reading SConsopts"
802for bdir in [ base_dir ] + extras_dir_list:
803    if not isdir(bdir):
804        print "Error: directory '%s' does not exist" % bdir
805        Exit(1)
806    for root, dirs, files in os.walk(bdir):
807        if 'SConsopts' in files:
808            if GetOption('verbose'):
809                print "Reading", joinpath(root, 'SConsopts')
810            SConscript(joinpath(root, 'SConsopts'))
811
812all_isa_list.sort()
813
814sticky_vars.AddVariables(
815    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
816    ListVariable('CPU_MODELS', 'CPU models',
817                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
818                 sorted(CpuModel.list)),
819    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
820    BoolVariable('FORCE_FAST_ALLOC',
821                 'Enable fast object allocator, even for gem5.debug', False),
822    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
823                 False),
824    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
825                 False),
826    BoolVariable('SS_COMPATIBLE_FP',
827                 'Make floating-point results compatible with SimpleScalar',
828                 False),
829    BoolVariable('USE_SSE2',
830                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
831                 False),
832    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
833    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
834    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
835    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
836    )
837
838# These variables get exported to #defines in config/*.hh (see src/SConscript).
839export_vars += ['USE_FENV', 'NO_FAST_ALLOC', 'FORCE_FAST_ALLOC',
840                'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', 'USE_CHECKER',
841                'TARGET_ISA', 'CP_ANNOTATE', 'USE_POSIX_CLOCK' ]
842
843###################################################
844#
845# Define a SCons builder for configuration flag headers.
846#
847###################################################
848
849# This function generates a config header file that #defines the
850# variable symbol to the current variable setting (0 or 1).  The source
851# operands are the name of the variable and a Value node containing the
852# value of the variable.
853def build_config_file(target, source, env):
854    (variable, value) = [s.get_contents() for s in source]
855    f = file(str(target[0]), 'w')
856    print >> f, '#define', variable, value
857    f.close()
858    return None
859
860# Combine the two functions into a scons Action object.
861config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
862
863# The emitter munges the source & target node lists to reflect what
864# we're really doing.
865def config_emitter(target, source, env):
866    # extract variable name from Builder arg
867    variable = str(target[0])
868    # True target is config header file
869    target = joinpath('config', variable.lower() + '.hh')
870    val = env[variable]
871    if isinstance(val, bool):
872        # Force value to 0/1
873        val = int(val)
874    elif isinstance(val, str):
875        val = '"' + val + '"'
876
877    # Sources are variable name & value (packaged in SCons Value nodes)
878    return ([target], [Value(variable), Value(val)])
879
880config_builder = Builder(emitter = config_emitter, action = config_action)
881
882main.Append(BUILDERS = { 'ConfigFile' : config_builder })
883
884# libelf build is shared across all configs in the build root.
885main.SConscript('ext/libelf/SConscript',
886                variant_dir = joinpath(build_root, 'libelf'))
887
888# gzstream build is shared across all configs in the build root.
889main.SConscript('ext/gzstream/SConscript',
890                variant_dir = joinpath(build_root, 'gzstream'))
891
892###################################################
893#
894# This function is used to set up a directory with switching headers
895#
896###################################################
897
898main['ALL_ISA_LIST'] = all_isa_list
899def make_switching_dir(dname, switch_headers, env):
900    # Generate the header.  target[0] is the full path of the output
901    # header to generate.  'source' is a dummy variable, since we get the
902    # list of ISAs from env['ALL_ISA_LIST'].
903    def gen_switch_hdr(target, source, env):
904        fname = str(target[0])
905        f = open(fname, 'w')
906        isa = env['TARGET_ISA'].lower()
907        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
908        f.close()
909
910    # Build SCons Action object. 'varlist' specifies env vars that this
911    # action depends on; when env['ALL_ISA_LIST'] changes these actions
912    # should get re-executed.
913    switch_hdr_action = MakeAction(gen_switch_hdr,
914                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
915
916    # Instantiate actions for each header
917    for hdr in switch_headers:
918        env.Command(hdr, [], switch_hdr_action)
919Export('make_switching_dir')
920
921###################################################
922#
923# Define build environments for selected configurations.
924#
925###################################################
926
927for variant_path in variant_paths:
928    print "Building in", variant_path
929
930    # Make a copy of the build-root environment to use for this config.
931    env = main.Clone()
932    env['BUILDDIR'] = variant_path
933
934    # variant_dir is the tail component of build path, and is used to
935    # determine the build parameters (e.g., 'ALPHA_SE')
936    (build_root, variant_dir) = splitpath(variant_path)
937
938    # Set env variables according to the build directory config.
939    sticky_vars.files = []
940    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
941    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
942    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
943    current_vars_file = joinpath(build_root, 'variables', variant_dir)
944    if isfile(current_vars_file):
945        sticky_vars.files.append(current_vars_file)
946        print "Using saved variables file %s" % current_vars_file
947    else:
948        # Build dir-specific variables file doesn't exist.
949
950        # Make sure the directory is there so we can create it later
951        opt_dir = dirname(current_vars_file)
952        if not isdir(opt_dir):
953            mkdir(opt_dir)
954
955        # Get default build variables from source tree.  Variables are
956        # normally determined by name of $VARIANT_DIR, but can be
957        # overridden by '--default=' arg on command line.
958        default = GetOption('default')
959        opts_dir = joinpath(main.root.abspath, 'build_opts')
960        if default:
961            default_vars_files = [joinpath(build_root, 'variables', default),
962                                  joinpath(opts_dir, default)]
963        else:
964            default_vars_files = [joinpath(opts_dir, variant_dir)]
965        existing_files = filter(isfile, default_vars_files)
966        if existing_files:
967            default_vars_file = existing_files[0]
968            sticky_vars.files.append(default_vars_file)
969            print "Variables file %s not found,\n  using defaults in %s" \
970                  % (current_vars_file, default_vars_file)
971        else:
972            print "Error: cannot find variables file %s or " \
973                  "default file(s) %s" \
974                  % (current_vars_file, ' or '.join(default_vars_files))
975            Exit(1)
976
977    # Apply current variable settings to env
978    sticky_vars.Update(env)
979
980    help_texts["local_vars"] += \
981        "Build variables for %s:\n" % variant_dir \
982                 + sticky_vars.GenerateHelpText(env)
983
984    # Process variable settings.
985
986    if not have_fenv and env['USE_FENV']:
987        print "Warning: <fenv.h> not available; " \
988              "forcing USE_FENV to False in", variant_dir + "."
989        env['USE_FENV'] = False
990
991    if not env['USE_FENV']:
992        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
993        print "         FP results may deviate slightly from other platforms."
994
995    if env['EFENCE']:
996        env.Append(LIBS=['efence'])
997
998    # Save sticky variable settings back to current variables file
999    sticky_vars.Save(current_vars_file, env)
1000
1001    if env['USE_SSE2']:
1002        env.Append(CCFLAGS=['-msse2'])
1003
1004    # The src/SConscript file sets up the build rules in 'env' according
1005    # to the configured variables.  It returns a list of environments,
1006    # one for each variant build (debug, opt, etc.)
1007    envList = SConscript('src/SConscript', variant_dir = variant_path,
1008                         exports = 'env')
1009
1010    # Set up the regression tests for each build.
1011    for e in envList:
1012        SConscript('tests/SConscript',
1013                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1014                   exports = { 'env' : e }, duplicate = False)
1015
1016# base help text
1017Help('''
1018Usage: scons [scons options] [build variables] [target(s)]
1019
1020Extra scons options:
1021%(options)s
1022
1023Global build variables:
1024%(global_vars)s
1025
1026%(local_vars)s
1027''' % help_texts)
1028