SConstruct revision 7727
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
4955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
5955SN/A# All rights reserved.
6955SN/A#
7955SN/A# Redistribution and use in source and binary forms, with or without
8955SN/A# modification, are permitted provided that the following conditions are
9955SN/A# met: redistributions of source code must retain the above copyright
10955SN/A# notice, this list of conditions and the following disclaimer;
11955SN/A# redistributions in binary form must reproduce the above copyright
12955SN/A# notice, this list of conditions and the following disclaimer in the
13955SN/A# documentation and/or other materials provided with the distribution;
14955SN/A# neither the name of the copyright holders nor the names of its
15955SN/A# contributors may be used to endorse or promote products derived from
16955SN/A# this software without specific prior written permission.
17955SN/A#
18955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
282665Ssaidi@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
292665Ssaidi@eecs.umich.edu#
30955SN/A# Authors: Steve Reinhardt
31955SN/A#          Nathan Binkert
32955SN/A
33955SN/A###################################################
34955SN/A#
352632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
362632Sstever@eecs.umich.edu#
372632Sstever@eecs.umich.edu# While in this directory ('m5'), just type 'scons' to build the default
382632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
39955SN/A# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
402632Sstever@eecs.umich.edu# the optimized full-system version).
412632Sstever@eecs.umich.edu#
422761Sstever@eecs.umich.edu# You can build M5 in a different directory as long as there is a
432632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
442632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
452632Sstever@eecs.umich.edu# built for the same host system.
462761Sstever@eecs.umich.edu#
472761Sstever@eecs.umich.edu# Examples:
482761Sstever@eecs.umich.edu#
492632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
502632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
512761Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
522761Sstever@eecs.umich.edu#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
532761Sstever@eecs.umich.edu#
542761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
552761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
562632Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
572632Sstever@eecs.umich.edu#   file.
582632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
592632Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
602632Sstever@eecs.umich.edu#
612632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
622632Sstever@eecs.umich.edu# 'm5' directory (or use -u or -C to tell scons where to find this
63955SN/A# file), you can use 'scons -h' to print all the M5-specific build
64955SN/A# options as well.
65955SN/A#
66955SN/A###################################################
67955SN/A
68955SN/A# Check for recent-enough Python and SCons versions.
69955SN/Atry:
702656Sstever@eecs.umich.edu    # Really old versions of scons only take two options for the
712656Sstever@eecs.umich.edu    # function, so check once without the revision and once with the
722656Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
732656Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
742656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
752656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
762656Sstever@eecs.umich.eduexcept SystemExit, e:
772653Sstever@eecs.umich.edu    print """
782653Sstever@eecs.umich.eduFor more details, see:
792653Sstever@eecs.umich.edu    http://m5sim.org/wiki/index.php/Compiling_M5
802653Sstever@eecs.umich.edu"""
812653Sstever@eecs.umich.edu    raise
822653Sstever@eecs.umich.edu
832653Sstever@eecs.umich.edu# We ensure the python version early because we have stuff that
842653Sstever@eecs.umich.edu# requires python 2.4
852653Sstever@eecs.umich.edutry:
862653Sstever@eecs.umich.edu    EnsurePythonVersion(2, 4)
872653Sstever@eecs.umich.eduexcept SystemExit, e:
881852SN/A    print """
89955SN/AYou can use a non-default installation of the Python interpreter by
90955SN/Aeither (1) rearranging your PATH so that scons finds the non-default
91955SN/A'python' first or (2) explicitly invoking an alternative interpreter
922632Sstever@eecs.umich.eduon the scons script.
932632Sstever@eecs.umich.edu
94955SN/AFor more details, see:
951533SN/A    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
962632Sstever@eecs.umich.edu"""
971533SN/A    raise
98955SN/A
99955SN/A# Global Python includes
1002632Sstever@eecs.umich.eduimport os
1012632Sstever@eecs.umich.eduimport re
102955SN/Aimport subprocess
103955SN/Aimport sys
104955SN/A
105955SN/Afrom os import mkdir, environ
1062632Sstever@eecs.umich.edufrom os.path import abspath, basename, dirname, expanduser, normpath
107955SN/Afrom os.path import exists,  isdir, isfile
1082632Sstever@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
109955SN/A
110955SN/A# SCons includes
1112632Sstever@eecs.umich.eduimport SCons
1122632Sstever@eecs.umich.eduimport SCons.Node
1132632Sstever@eecs.umich.edu
1142632Sstever@eecs.umich.eduextra_python_paths = [
1152632Sstever@eecs.umich.edu    Dir('src/python').srcnode().abspath, # M5 includes
1162632Sstever@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1172632Sstever@eecs.umich.edu    ]
1182632Sstever@eecs.umich.edu    
1192632Sstever@eecs.umich.edusys.path[1:1] = extra_python_paths
1202632Sstever@eecs.umich.edu
1212632Sstever@eecs.umich.edufrom m5.util import compareVersions, readCommand
1222632Sstever@eecs.umich.edu
1232632Sstever@eecs.umich.edu########################################################################
1242632Sstever@eecs.umich.edu#
1252632Sstever@eecs.umich.edu# Set up the main build environment.
1262632Sstever@eecs.umich.edu#
1272632Sstever@eecs.umich.edu########################################################################
1282634Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
1292634Sstever@eecs.umich.edu                 'PYTHONPATH', 'RANLIB' ])
1302632Sstever@eecs.umich.edu
1312638Sstever@eecs.umich.eduuse_env = {}
1322632Sstever@eecs.umich.edufor key,val in os.environ.iteritems():
1332632Sstever@eecs.umich.edu    if key in use_vars or key.startswith("M5"):
1342632Sstever@eecs.umich.edu        use_env[key] = val
1352632Sstever@eecs.umich.edu
1362632Sstever@eecs.umich.edumain = Environment(ENV=use_env)
1372632Sstever@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
1381858SN/Amain.srcdir = Dir("src")     # The source directory
1392638Sstever@eecs.umich.edu
1402638Sstever@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
1412638Sstever@eecs.umich.edu# as well
1422638Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
1432638Sstever@eecs.umich.edu
1442638Sstever@eecs.umich.edu########################################################################
1452638Sstever@eecs.umich.edu#
1462638Sstever@eecs.umich.edu# Mercurial Stuff.
1472634Sstever@eecs.umich.edu#
1482634Sstever@eecs.umich.edu# If the M5 directory is a mercurial repository, we should do some
1492634Sstever@eecs.umich.edu# extra things.
150955SN/A#
151955SN/A########################################################################
152955SN/A
153955SN/Ahgdir = main.root.Dir(".hg")
154955SN/A
155955SN/Amercurial_style_message = """
156955SN/AYou're missing the M5 style hook.
157955SN/APlease install the hook so we can ensure that all code fits a common style.
1581858SN/A
1591858SN/AAll you'd need to do is add the following lines to your repository .hg/hgrc
1602632Sstever@eecs.umich.eduor your personal .hgrc
161955SN/A----------------
1621858SN/A
1631105SN/A[extensions]
1642667Sstever@eecs.umich.edustyle = %s/util/style.py
1652667Sstever@eecs.umich.edu
1662667Sstever@eecs.umich.edu[hooks]
1672667Sstever@eecs.umich.edupretxncommit.style = python:style.check_whitespace
1682667Sstever@eecs.umich.edu""" % (main.root)
1692667Sstever@eecs.umich.edu
1701869SN/Amercurial_bin_not_found = """
1711869SN/AMercurial binary cannot be found, unfortunately this means that we
1721869SN/Acannot easily determine the version of M5 that you are running and
1731869SN/Athis makes error messages more difficult to collect.  Please consider
1741869SN/Ainstalling mercurial if you choose to post an error message
1751065SN/A"""
1762632Sstever@eecs.umich.edu
1772632Sstever@eecs.umich.edumercurial_lib_not_found = """
178955SN/AMercurial libraries cannot be found, ignoring style hook
1791858SN/AIf you are actually a M5 developer, please fix this and
1801858SN/Arun the style hook. It is important.
1811858SN/A"""
1821858SN/A
1831851SN/Ahg_info = "Unknown"
1841851SN/Aif hgdir.exists():
1851858SN/A    # 1) Grab repository revision if we know it.
1862632Sstever@eecs.umich.edu    cmd = "hg id -n -i -t -b"
187955SN/A    try:
1882656Sstever@eecs.umich.edu        hg_info = readCommand(cmd, cwd=main.root.abspath).strip()
1892656Sstever@eecs.umich.edu    except OSError:
1902656Sstever@eecs.umich.edu        print mercurial_bin_not_found
1912656Sstever@eecs.umich.edu
1922656Sstever@eecs.umich.edu    # 2) Ensure that the style hook is in place.
1932656Sstever@eecs.umich.edu    try:
1942656Sstever@eecs.umich.edu        ui = None
1952656Sstever@eecs.umich.edu        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
1962656Sstever@eecs.umich.edu            from mercurial import ui
1972656Sstever@eecs.umich.edu            ui = ui.ui()
1982656Sstever@eecs.umich.edu    except ImportError:
1992656Sstever@eecs.umich.edu        print mercurial_lib_not_found
2002656Sstever@eecs.umich.edu
2012656Sstever@eecs.umich.edu    if ui is not None:
2022656Sstever@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2032656Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2042655Sstever@eecs.umich.edu
2052667Sstever@eecs.umich.edu        if not style_hook:
2062667Sstever@eecs.umich.edu            print mercurial_style_message
2072667Sstever@eecs.umich.edu            sys.exit(1)
2082667Sstever@eecs.umich.eduelse:
2092667Sstever@eecs.umich.edu    print ".hg directory not found"
2102667Sstever@eecs.umich.edu
2112667Sstever@eecs.umich.edumain['HG_INFO'] = hg_info
2122667Sstever@eecs.umich.edu
2132667Sstever@eecs.umich.edu###################################################
2142667Sstever@eecs.umich.edu#
2152667Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
2162667Sstever@eecs.umich.edu# the target(s).
2172667Sstever@eecs.umich.edu#
2182655Sstever@eecs.umich.edu###################################################
2191858SN/A
2201858SN/A# Find default configuration & binary.
2212638Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
2222638Sstever@eecs.umich.edu
2232638Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2242638Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2252638Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2261858SN/A        if l[i] == elt:
2271858SN/A            return i
2281858SN/A    raise ValueError, "element not found"
2291858SN/A
2301858SN/A# Each target must have 'build' in the interior of the path; the
2311858SN/A# directory below this will determine the build parameters.  For
2321858SN/A# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2331859SN/A# recognize that ALPHA_SE specifies the configuration because it
2341858SN/A# follow 'build' in the bulid path.
2351858SN/A
2361858SN/A# Generate absolute paths to targets so we can see where the build dir is
2371859SN/Aif COMMAND_LINE_TARGETS:
2381859SN/A    # Ask SCons which directory it was invoked from
2391862SN/A    launch_dir = GetLaunchDir()
2401862SN/A    # Make targets relative to invocation directory
2411862SN/A    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2421862SN/A                    COMMAND_LINE_TARGETS]
2431859SN/Aelse:
2441859SN/A    # Default targets are relative to root of tree
2451963SN/A    abs_targets = [ normpath(joinpath(main.root.abspath, str(x))) for x in \
2461963SN/A                    DEFAULT_TARGETS]
2471859SN/A
2481859SN/A
2491859SN/A# Generate a list of the unique build roots and configs that the
2501859SN/A# collected targets reference.
2511859SN/Avariant_paths = []
2521859SN/Abuild_root = None
2531859SN/Afor t in abs_targets:
2541859SN/A    path_dirs = t.split('/')
2551862SN/A    try:
2561859SN/A        build_top = rfind(path_dirs, 'build', -2)
2571859SN/A    except:
2581859SN/A        print "Error: no non-leaf 'build' dir found on target path", t
2591858SN/A        Exit(1)
2601858SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2612139SN/A    if not build_root:
2622139SN/A        build_root = this_build_root
2632139SN/A    else:
2642155SN/A        if this_build_root != build_root:
2652623SN/A            print "Error: build targets not under same build root\n"\
2662733Sktlim@umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
2672733Sktlim@umich.edu            Exit(1)
2682155SN/A    variant_path = joinpath('/',*path_dirs[:build_top+2])
2691869SN/A    if variant_path not in variant_paths:
2701869SN/A        variant_paths.append(variant_path)
2711869SN/A
2721869SN/A# Make sure build_root exists (might not if this is the first build there)
2731869SN/Aif not isdir(build_root):
2742139SN/A    mkdir(build_root)
2751869SN/A
2762508SN/AExport('main')
2772508SN/A
2782508SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
2792508SN/A
2802635Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2812635Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
2821869SN/A# file to file~ then copies to file, breaking the link.  Symbolic
2831869SN/A# (soft) links work better.
2841869SN/Amain.SetOption('duplicate', 'soft-copy')
2851869SN/A
2861869SN/A#
2871869SN/A# Set up global sticky variables... these are common to an entire build
2881869SN/A# tree (not specific to a particular build like ALPHA_SE)
2891869SN/A#
2901965SN/A
2911965SN/A# Variable validators & converters for global sticky variables
2921965SN/Adef PathListMakeAbsolute(val):
2931869SN/A    if not val:
2941869SN/A        return val
2952733Sktlim@umich.edu    f = lambda p: abspath(expanduser(p))
2961869SN/A    return ':'.join(map(f, val.split(':')))
2971884SN/A
2981884SN/Adef PathListAllExist(key, val, env):
2991884SN/A    if not val:
3001869SN/A        return
3011858SN/A    paths = val.split(':')
3021869SN/A    for path in paths:
3031869SN/A        if not isdir(path):
3041869SN/A            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3051869SN/A
3061869SN/Aglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3071858SN/A
3082761Sstever@eecs.umich.eduglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3091869SN/A
3102733Sktlim@umich.eduglobal_sticky_vars.AddVariables(
3112733Sktlim@umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3121869SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3131869SN/A    ('BATCH', 'Use batch pool for build and tests', False),
3141869SN/A    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3151869SN/A    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3161869SN/A    ('EXTRAS', 'Add Extra directories to the compilation', '',
3171869SN/A     PathListAllExist, PathListMakeAbsolute),
3181858SN/A    )
319955SN/A
320955SN/A# base help text
3211869SN/Ahelp_text = '''
3221869SN/AUsage: scons [scons options] [build options] [target(s)]
3231869SN/A
3241869SN/AGlobal sticky options:
3251869SN/A'''
3261869SN/A
3271869SN/A# Update main environment with values from ARGUMENTS & global_sticky_vars_file
3281869SN/Aglobal_sticky_vars.Update(main)
3291869SN/A
3301869SN/Ahelp_text += global_sticky_vars.GenerateHelpText(main)
3311869SN/A
3321869SN/A# Save sticky variable settings back to current variables file
3331869SN/Aglobal_sticky_vars.Save(global_sticky_vars_file, main)
3341869SN/A
3351869SN/A# Parse EXTRAS variable to build list of all directories where we're
3361869SN/A# look for sources etc.  This list is exported as base_dir_list.
3371869SN/Abase_dir = main.srcdir.abspath
3381869SN/Aif main['EXTRAS']:
3391869SN/A    extras_dir_list = main['EXTRAS'].split(':')
3401869SN/Aelse:
3411869SN/A    extras_dir_list = []
3421869SN/A
3431869SN/AExport('base_dir')
3441869SN/AExport('extras_dir_list')
3451869SN/A
3461869SN/A# the ext directory should be on the #includes path
3471869SN/Amain.Append(CPPPATH=[Dir('ext')])
3481869SN/A
3491869SN/ACXX_version = readCommand([main['CXX'],'--version'], exception=False)
3501869SN/ACXX_V = readCommand([main['CXX'],'-V'], exception=False)
3511869SN/A
3521869SN/Amain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3531869SN/Amain['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
3541869SN/Amain['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
3551869SN/Aif main['GCC'] + main['SUNCC'] + main['ICC'] > 1:
3561869SN/A    print 'Error: How can we have two at the same time?'
3571869SN/A    Exit(1)
3581869SN/A
3591869SN/A# Set up default C++ compiler flags
3602655Sstever@eecs.umich.eduif main['GCC']:
3612655Sstever@eecs.umich.edu    main.Append(CCFLAGS='-pipe')
3622655Sstever@eecs.umich.edu    main.Append(CCFLAGS='-fno-strict-aliasing')
3632655Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
3642655Sstever@eecs.umich.edu    main.Append(CXXFLAGS='-Wno-deprecated')
3652655Sstever@eecs.umich.edu    # Read the GCC version to check for versions with bugs
3662655Sstever@eecs.umich.edu    # Note CCVERSION doesn't work here because it is run with the CC
3672655Sstever@eecs.umich.edu    # before we override it from the command line
3682655Sstever@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3692655Sstever@eecs.umich.edu    if not compareVersions(gcc_version, '4.4.1') or \
3702655Sstever@eecs.umich.edu       not compareVersions(gcc_version, '4.4.2'):
3712655Sstever@eecs.umich.edu        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
3722655Sstever@eecs.umich.edu        main.Append(CCFLAGS='-fno-tree-vectorize')
3732655Sstever@eecs.umich.eduelif main['ICC']:
3742655Sstever@eecs.umich.edu    pass #Fix me... add warning flags once we clean up icc warnings
3752655Sstever@eecs.umich.eduelif main['SUNCC']:
3762655Sstever@eecs.umich.edu    main.Append(CCFLAGS='-Qoption ccfe')
3772655Sstever@eecs.umich.edu    main.Append(CCFLAGS='-features=gcc')
3782655Sstever@eecs.umich.edu    main.Append(CCFLAGS='-features=extensions')
3792655Sstever@eecs.umich.edu    main.Append(CCFLAGS='-library=stlport4')
3802655Sstever@eecs.umich.edu    main.Append(CCFLAGS='-xar')
3812655Sstever@eecs.umich.edu    #main.Append(CCFLAGS='-instances=semiexplicit')
3822655Sstever@eecs.umich.eduelse:
3832655Sstever@eecs.umich.edu    print 'Error: Don\'t know what compiler options to use for your compiler.'
3842655Sstever@eecs.umich.edu    print '       Please fix SConstruct and src/SConscript and try again.'
3852655Sstever@eecs.umich.edu    Exit(1)
3862634Sstever@eecs.umich.edu
3872634Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
3882634Sstever@eecs.umich.edumain['YACCFLAGS'] = '-d'
3892634Sstever@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
3902634Sstever@eecs.umich.edu
3912634Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
3922638Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
3932638Sstever@eecs.umich.eduif main['BATCH']:
3942638Sstever@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
3952638Sstever@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
3962638Sstever@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
3971869SN/A    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
3981869SN/A    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
399955SN/A
400955SN/Aif sys.platform == 'cygwin':
401955SN/A    # cygwin has some header file issues...
402955SN/A    main.Append(CCFLAGS="-Wno-uninitialized")
4031858SN/A
4041858SN/A# Check for SWIG
4051858SN/Aif not main.has_key('SWIG'):
4062632Sstever@eecs.umich.edu    print 'Error: SWIG utility not found.'
4072632Sstever@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
4082632Sstever@eecs.umich.edu    Exit(1)
4092632Sstever@eecs.umich.edu
4102632Sstever@eecs.umich.edu# Check for appropriate SWIG version
4112634Sstever@eecs.umich.eduswig_version = readCommand(('swig', '-version'), exception='').split()
4122638Sstever@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
4132023SN/Aif len(swig_version) < 3 or \
4142632Sstever@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
4152632Sstever@eecs.umich.edu    print 'Error determining SWIG version.'
4162632Sstever@eecs.umich.edu    Exit(1)
4172632Sstever@eecs.umich.edu
4182632Sstever@eecs.umich.edumin_swig_version = '1.3.28'
4192632Sstever@eecs.umich.eduif compareVersions(swig_version[2], min_swig_version) < 0:
4202632Sstever@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
4212632Sstever@eecs.umich.edu    print '       Installed version:', swig_version[2]
4222632Sstever@eecs.umich.edu    Exit(1)
4232632Sstever@eecs.umich.edu
4242632Sstever@eecs.umich.edu# Set up SWIG flags & scanner
4252023SN/Aswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
4262632Sstever@eecs.umich.edumain.Append(SWIGFLAGS=swig_flags)
4272632Sstever@eecs.umich.edu
4281889SN/A# filter out all existing swig scanners, they mess up the dependency
4291889SN/A# stuff for some reason
4302632Sstever@eecs.umich.eduscanners = []
4312632Sstever@eecs.umich.edufor scanner in main['SCANNERS']:
4322632Sstever@eecs.umich.edu    skeys = scanner.skeys
4332632Sstever@eecs.umich.edu    if skeys == '.i':
4342632Sstever@eecs.umich.edu        continue
4352632Sstever@eecs.umich.edu
4362632Sstever@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
4372632Sstever@eecs.umich.edu        continue
4382632Sstever@eecs.umich.edu
4392632Sstever@eecs.umich.edu    scanners.append(scanner)
4402632Sstever@eecs.umich.edu
4412632Sstever@eecs.umich.edu# add the new swig scanner that we like better
4422632Sstever@eecs.umich.edufrom SCons.Scanner import ClassicCPP as CPPScanner
4432632Sstever@eecs.umich.eduswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
4441888SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
4451888SN/A
4461869SN/A# replace the scanners list that has what we want
4471869SN/Amain['SCANNERS'] = scanners
4481858SN/A
4492598SN/A# Add a custom Check function to the Configure context so that we can
4502598SN/A# figure out if the compiler adds leading underscores to global
4512598SN/A# variables.  This is needed for the autogenerated asm files that we
4522598SN/A# use for embedding the python code.
4532598SN/Adef CheckLeading(context):
4541858SN/A    context.Message("Checking for leading underscore in global variables...")
4551858SN/A    # 1) Define a global variable called x from asm so the C compiler
4561858SN/A    #    won't change the symbol at all.
4571858SN/A    # 2) Declare that variable.
4581858SN/A    # 3) Use the variable
4591858SN/A    #
4601858SN/A    # If the compiler prepends an underscore, this will successfully
4611858SN/A    # link because the external symbol 'x' will be called '_x' which
4621858SN/A    # was defined by the asm statement.  If the compiler does not
4631871SN/A    # prepend an underscore, this will not successfully link because
4641858SN/A    # '_x' will have been defined by assembly, while the C portion of
4651858SN/A    # the code will be trying to use 'x'
4661858SN/A    ret = context.TryLink('''
4671858SN/A        asm(".globl _x; _x: .byte 0");
4681858SN/A        extern int x;
4691858SN/A        int main() { return x; }
4701858SN/A        ''', extension=".c")
4711858SN/A    context.env.Append(LEADING_UNDERSCORE=ret)
4721858SN/A    context.Result(ret)
4731858SN/A    return ret
4741858SN/A
4751859SN/A# Platform-specific configuration.  Note again that we assume that all
4761859SN/A# builds under a given build root run on the same host platform.
4771869SN/Aconf = Configure(main,
4782733Sktlim@umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
4792733Sktlim@umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
4802733Sktlim@umich.edu                 custom_tests = { 'CheckLeading' : CheckLeading })
4812733Sktlim@umich.edu
4821888SN/A# Check for leading underscores.  Don't really need to worry either
4832632Sstever@eecs.umich.edu# way so don't need to check the return code.
4841869SN/Aconf.CheckLeading()
4851884SN/A
4861884SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
4871884SN/Atry:
4881884SN/A    import platform
4891884SN/A    uname = platform.uname()
4901884SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
4911965SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
4921965SN/A            main.Append(CCFLAGS='-arch x86_64')
4931965SN/A            main.Append(CFLAGS='-arch x86_64')
4942761Sstever@eecs.umich.edu            main.Append(LINKFLAGS='-arch x86_64')
4951869SN/A            main.Append(ASFLAGS='-arch x86_64')
4961869SN/Aexcept:
4972632Sstever@eecs.umich.edu    pass
4982667Sstever@eecs.umich.edu
4991869SN/A# Recent versions of scons substitute a "Null" object for Configure()
5001869SN/A# when configuration isn't necessary, e.g., if the "--help" option is
5012632Sstever@eecs.umich.edu# present.  Unfortuantely this Null object always returns false,
5022632Sstever@eecs.umich.edu# breaking all our configuration checks.  We replace it with our own
5032632Sstever@eecs.umich.edu# more optimistic null object that returns True instead.
5042632Sstever@eecs.umich.eduif not conf:
505955SN/A    def NullCheck(*args, **kwargs):
5062598SN/A        return True
5072598SN/A
508955SN/A    class NullConf:
509955SN/A        def __init__(self, env):
510955SN/A            self.env = env
5111530SN/A        def Finish(self):
512955SN/A            return self.env
513955SN/A        def __getattr__(self, mname):
514955SN/A            return NullCheck
515
516    conf = NullConf(main)
517
518# Find Python include and library directories for embedding the
519# interpreter.  For consistency, we will use the same Python
520# installation used to run scons (and thus this script).  If you want
521# to link in an alternate version, see above for instructions on how
522# to invoke scons with a different copy of the Python interpreter.
523from distutils import sysconfig
524
525py_getvar = sysconfig.get_config_var
526
527py_debug = getattr(sys, 'pydebug', False)
528py_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
529
530py_general_include = sysconfig.get_python_inc()
531py_platform_include = sysconfig.get_python_inc(plat_specific=True)
532py_includes = [ py_general_include ]
533if py_platform_include != py_general_include:
534    py_includes.append(py_platform_include)
535
536py_lib_path = [ py_getvar('LIBDIR') ]
537# add the prefix/lib/pythonX.Y/config dir, but only if there is no
538# shared library in prefix/lib/.
539if not py_getvar('Py_ENABLE_SHARED'):
540    py_lib_path.append(py_getvar('LIBPL'))
541
542py_libs = []
543for lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
544    assert lib.startswith('-l')
545    lib = lib[2:]   
546    if lib not in py_libs:
547        py_libs.append(lib)
548py_libs.append(py_version)
549
550main.Append(CPPPATH=py_includes)
551main.Append(LIBPATH=py_lib_path)
552
553# Cache build files in the supplied directory.
554if main['M5_BUILD_CACHE']:
555    print 'Using build cache located at', main['M5_BUILD_CACHE']
556    CacheDir(main['M5_BUILD_CACHE'])
557
558
559# verify that this stuff works
560if not conf.CheckHeader('Python.h', '<>'):
561    print "Error: can't find Python.h header in", py_includes
562    Exit(1)
563
564for lib in py_libs:
565    if not conf.CheckLib(lib):
566        print "Error: can't find library %s required by python" % lib
567        Exit(1)
568
569# On Solaris you need to use libsocket for socket ops
570if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
571   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
572       print "Can't find library with socket calls (e.g. accept())"
573       Exit(1)
574
575# Check for zlib.  If the check passes, libz will be automatically
576# added to the LIBS environment variable.
577if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
578    print 'Error: did not find needed zlib compression library '\
579          'and/or zlib.h header file.'
580    print '       Please install zlib and try again.'
581    Exit(1)
582
583# Check for <fenv.h> (C99 FP environment control)
584have_fenv = conf.CheckHeader('fenv.h', '<>')
585if not have_fenv:
586    print "Warning: Header file <fenv.h> not found."
587    print "         This host has no IEEE FP rounding mode control."
588
589######################################################################
590#
591# Check for mysql.
592#
593mysql_config = WhereIs('mysql_config')
594have_mysql = bool(mysql_config)
595
596# Check MySQL version.
597if have_mysql:
598    mysql_version = readCommand(mysql_config + ' --version')
599    min_mysql_version = '4.1'
600    if compareVersions(mysql_version, min_mysql_version) < 0:
601        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
602        print '         Version', mysql_version, 'detected.'
603        have_mysql = False
604
605# Set up mysql_config commands.
606if have_mysql:
607    mysql_config_include = mysql_config + ' --include'
608    if os.system(mysql_config_include + ' > /dev/null') != 0:
609        # older mysql_config versions don't support --include, use
610        # --cflags instead
611        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
612    # This seems to work in all versions
613    mysql_config_libs = mysql_config + ' --libs'
614
615######################################################################
616#
617# Finish the configuration
618#
619main = conf.Finish()
620
621######################################################################
622#
623# Collect all non-global variables
624#
625
626# Define the universe of supported ISAs
627all_isa_list = [ ]
628Export('all_isa_list')
629
630class CpuModel(object):
631    '''The CpuModel class encapsulates everything the ISA parser needs to
632    know about a particular CPU model.'''
633
634    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
635    dict = {}
636    list = []
637    defaults = []
638
639    # Constructor.  Automatically adds models to CpuModel.dict.
640    def __init__(self, name, filename, includes, strings, default=False):
641        self.name = name           # name of model
642        self.filename = filename   # filename for output exec code
643        self.includes = includes   # include files needed in exec file
644        # The 'strings' dict holds all the per-CPU symbols we can
645        # substitute into templates etc.
646        self.strings = strings
647
648        # This cpu is enabled by default
649        self.default = default
650
651        # Add self to dict
652        if name in CpuModel.dict:
653            raise AttributeError, "CpuModel '%s' already registered" % name
654        CpuModel.dict[name] = self
655        CpuModel.list.append(name)
656
657Export('CpuModel')
658
659# Sticky variables get saved in the variables file so they persist from
660# one invocation to the next (unless overridden, in which case the new
661# value becomes sticky).
662sticky_vars = Variables(args=ARGUMENTS)
663Export('sticky_vars')
664
665# Sticky variables that should be exported
666export_vars = []
667Export('export_vars')
668
669# Non-sticky variables only apply to the current build.
670nonsticky_vars = Variables(args=ARGUMENTS)
671Export('nonsticky_vars')
672
673# Walk the tree and execute all SConsopts scripts that wil add to the
674# above variables
675for bdir in [ base_dir ] + extras_dir_list:
676    for root, dirs, files in os.walk(bdir):
677        if 'SConsopts' in files:
678            print "Reading", joinpath(root, 'SConsopts')
679            SConscript(joinpath(root, 'SConsopts'))
680
681all_isa_list.sort()
682
683sticky_vars.AddVariables(
684    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
685    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
686    ListVariable('CPU_MODELS', 'CPU models',
687                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
688                 sorted(CpuModel.list)),
689    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
690    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
691                 False),
692    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
693                 False),
694    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
695                 False),
696    BoolVariable('SS_COMPATIBLE_FP',
697                 'Make floating-point results compatible with SimpleScalar',
698                 False),
699    BoolVariable('USE_SSE2',
700                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
701                 False),
702    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
703    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
704    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
705    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
706    BoolVariable('RUBY', 'Build with Ruby', False),
707    )
708
709nonsticky_vars.AddVariables(
710    BoolVariable('update_ref', 'Update test reference outputs', False)
711    )
712
713# These variables get exported to #defines in config/*.hh (see src/SConscript).
714export_vars += ['FULL_SYSTEM', 'USE_FENV', 'USE_MYSQL',
715                'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', 'FAST_ALLOC_STATS',
716                'SS_COMPATIBLE_FP', 'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
717
718###################################################
719#
720# Define a SCons builder for configuration flag headers.
721#
722###################################################
723
724# This function generates a config header file that #defines the
725# variable symbol to the current variable setting (0 or 1).  The source
726# operands are the name of the variable and a Value node containing the
727# value of the variable.
728def build_config_file(target, source, env):
729    (variable, value) = [s.get_contents() for s in source]
730    f = file(str(target[0]), 'w')
731    print >> f, '#define', variable, value
732    f.close()
733    return None
734
735# Generate the message to be printed when building the config file.
736def build_config_file_string(target, source, env):
737    (variable, value) = [s.get_contents() for s in source]
738    return "Defining %s as %s in %s." % (variable, value, target[0])
739
740# Combine the two functions into a scons Action object.
741config_action = Action(build_config_file, build_config_file_string)
742
743# The emitter munges the source & target node lists to reflect what
744# we're really doing.
745def config_emitter(target, source, env):
746    # extract variable name from Builder arg
747    variable = str(target[0])
748    # True target is config header file
749    target = joinpath('config', variable.lower() + '.hh')
750    val = env[variable]
751    if isinstance(val, bool):
752        # Force value to 0/1
753        val = int(val)
754    elif isinstance(val, str):
755        val = '"' + val + '"'
756
757    # Sources are variable name & value (packaged in SCons Value nodes)
758    return ([target], [Value(variable), Value(val)])
759
760config_builder = Builder(emitter = config_emitter, action = config_action)
761
762main.Append(BUILDERS = { 'ConfigFile' : config_builder })
763
764# libelf build is shared across all configs in the build root.
765main.SConscript('ext/libelf/SConscript',
766                variant_dir = joinpath(build_root, 'libelf'))
767
768# gzstream build is shared across all configs in the build root.
769main.SConscript('ext/gzstream/SConscript',
770                variant_dir = joinpath(build_root, 'gzstream'))
771
772###################################################
773#
774# This function is used to set up a directory with switching headers
775#
776###################################################
777
778main['ALL_ISA_LIST'] = all_isa_list
779def make_switching_dir(dname, switch_headers, env):
780    # Generate the header.  target[0] is the full path of the output
781    # header to generate.  'source' is a dummy variable, since we get the
782    # list of ISAs from env['ALL_ISA_LIST'].
783    def gen_switch_hdr(target, source, env):
784        fname = str(target[0])
785        f = open(fname, 'w')
786        isa = env['TARGET_ISA'].lower()
787        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
788        f.close()
789
790    # String to print when generating header
791    def gen_switch_hdr_string(target, source, env):
792        return "Generating switch header " + str(target[0])
793
794    # Build SCons Action object. 'varlist' specifies env vars that this
795    # action depends on; when env['ALL_ISA_LIST'] changes these actions
796    # should get re-executed.
797    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
798                               varlist=['ALL_ISA_LIST'])
799
800    # Instantiate actions for each header
801    for hdr in switch_headers:
802        env.Command(hdr, [], switch_hdr_action)
803Export('make_switching_dir')
804
805###################################################
806#
807# Define build environments for selected configurations.
808#
809###################################################
810
811for variant_path in variant_paths:
812    print "Building in", variant_path
813
814    # Make a copy of the build-root environment to use for this config.
815    env = main.Clone()
816    env['BUILDDIR'] = variant_path
817
818    # variant_dir is the tail component of build path, and is used to
819    # determine the build parameters (e.g., 'ALPHA_SE')
820    (build_root, variant_dir) = splitpath(variant_path)
821
822    # Set env variables according to the build directory config.
823    sticky_vars.files = []
824    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
825    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
826    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
827    current_vars_file = joinpath(build_root, 'variables', variant_dir)
828    if isfile(current_vars_file):
829        sticky_vars.files.append(current_vars_file)
830        print "Using saved variables file %s" % current_vars_file
831    else:
832        # Build dir-specific variables file doesn't exist.
833
834        # Make sure the directory is there so we can create it later
835        opt_dir = dirname(current_vars_file)
836        if not isdir(opt_dir):
837            mkdir(opt_dir)
838
839        # Get default build variables from source tree.  Variables are
840        # normally determined by name of $VARIANT_DIR, but can be
841        # overriden by 'default=' arg on command line.
842        default_vars_file = joinpath('build_opts',
843                                     ARGUMENTS.get('default', variant_dir))
844        if isfile(default_vars_file):
845            sticky_vars.files.append(default_vars_file)
846            print "Variables file %s not found,\n  using defaults in %s" \
847                  % (current_vars_file, default_vars_file)
848        else:
849            print "Error: cannot find variables file %s or %s" \
850                  % (current_vars_file, default_vars_file)
851            Exit(1)
852
853    # Apply current variable settings to env
854    sticky_vars.Update(env)
855    nonsticky_vars.Update(env)
856
857    help_text += "\nSticky variables for %s:\n" % variant_dir \
858                 + sticky_vars.GenerateHelpText(env) \
859                 + "\nNon-sticky variables for %s:\n" % variant_dir \
860                 + nonsticky_vars.GenerateHelpText(env)
861
862    # Process variable settings.
863
864    if not have_fenv and env['USE_FENV']:
865        print "Warning: <fenv.h> not available; " \
866              "forcing USE_FENV to False in", variant_dir + "."
867        env['USE_FENV'] = False
868
869    if not env['USE_FENV']:
870        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
871        print "         FP results may deviate slightly from other platforms."
872
873    if env['EFENCE']:
874        env.Append(LIBS=['efence'])
875
876    if env['USE_MYSQL']:
877        if not have_mysql:
878            print "Warning: MySQL not available; " \
879                  "forcing USE_MYSQL to False in", variant_dir + "."
880            env['USE_MYSQL'] = False
881        else:
882            print "Compiling in", variant_dir, "with MySQL support."
883            env.ParseConfig(mysql_config_libs)
884            env.ParseConfig(mysql_config_include)
885
886    # Save sticky variable settings back to current variables file
887    sticky_vars.Save(current_vars_file, env)
888
889    if env['USE_SSE2']:
890        env.Append(CCFLAGS='-msse2')
891
892    # The src/SConscript file sets up the build rules in 'env' according
893    # to the configured variables.  It returns a list of environments,
894    # one for each variant build (debug, opt, etc.)
895    envList = SConscript('src/SConscript', variant_dir = variant_path,
896                         exports = 'env')
897
898    # Set up the regression tests for each build.
899    for e in envList:
900        SConscript('tests/SConscript',
901                   variant_dir = joinpath(variant_path, 'tests', e.Label),
902                   exports = { 'env' : e }, duplicate = False)
903
904Help(help_text)
905