SConstruct revision 5742
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2004-2005 The Regents of The University of Michigan
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# Redistribution and use in source and binary forms, with or without
79812Sandreas.hansson@arm.com# modification, are permitted provided that the following conditions are
89812Sandreas.hansson@arm.com# met: redistributions of source code must retain the above copyright
99812Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer;
109812Sandreas.hansson@arm.com# redistributions in binary form must reproduce the above copyright
119812Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer in the
129812Sandreas.hansson@arm.com# documentation and/or other materials provided with the distribution;
139812Sandreas.hansson@arm.com# neither the name of the copyright holders nor the names of its
149812Sandreas.hansson@arm.com# contributors may be used to endorse or promote products derived from
157816Ssteve.reinhardt@amd.com# this software without specific prior written permission.
165871Snate@binkert.org#
171762SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28955SN/A#
29955SN/A# Authors: Steve Reinhardt
30955SN/A
31955SN/A###################################################
32955SN/A#
33955SN/A# SCons top-level build description (SConstruct) file.
34955SN/A#
35955SN/A# While in this directory ('m5'), just type 'scons' to build the default
36955SN/A# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
37955SN/A# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
38955SN/A# the optimized full-system version).
39955SN/A#
40955SN/A# You can build M5 in a different directory as long as there is a
41955SN/A# 'build/<CONFIG>' somewhere along the target path.  The build system
422665Ssaidi@eecs.umich.edu# expects that all configs under the same build directory are being
432665Ssaidi@eecs.umich.edu# built for the same host system.
445863Snate@binkert.org#
45955SN/A# Examples:
46955SN/A#
47955SN/A#   The following two commands are equivalent.  The '-u' option tells
48955SN/A#   scons to search up the directory tree for this SConstruct file.
49955SN/A#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
508878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
512632Sstever@eecs.umich.edu#
528878Ssteve.reinhardt@amd.com#   The following two commands are equivalent and demonstrate building
532632Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
54955SN/A#   scons to chdir to the specified directory to find this SConstruct
558878Ssteve.reinhardt@amd.com#   file.
562632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
572761Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
582632Sstever@eecs.umich.edu#
592632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
602632Sstever@eecs.umich.edu# 'm5' directory (or use -u or -C to tell scons where to find this
612761Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the M5-specific build
622761Sstever@eecs.umich.edu# options as well.
632761Sstever@eecs.umich.edu#
648878Ssteve.reinhardt@amd.com###################################################
658878Ssteve.reinhardt@amd.com
662761Sstever@eecs.umich.eduimport sys
672761Sstever@eecs.umich.eduimport os
682761Sstever@eecs.umich.eduimport re
692761Sstever@eecs.umich.edu
702761Sstever@eecs.umich.edufrom os.path import isdir, isfile, join as joinpath
718878Ssteve.reinhardt@amd.com
728878Ssteve.reinhardt@amd.comimport SCons
732632Sstever@eecs.umich.edu
742632Sstever@eecs.umich.edu# Check for recent-enough Python and SCons versions.  If your system's
758878Ssteve.reinhardt@amd.com# default installation of Python is not recent enough, you can use a
768878Ssteve.reinhardt@amd.com# non-default installation of the Python interpreter by either (1)
772632Sstever@eecs.umich.edu# rearranging your PATH so that scons finds the non-default 'python'
78955SN/A# first or (2) explicitly invoking an alternative interpreter on the
79955SN/A# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
80955SN/AEnsurePythonVersion(2,4)
8112563Sgabeblack@google.com
8212563Sgabeblack@google.com# Import subprocess after we check the version since it doesn't exist in
836654Snate@binkert.org# Python < 2.4.
8410196SCurtis.Dunham@arm.comimport subprocess
85955SN/A
865396Ssaidi@eecs.umich.edu# helper function: compare arrays or strings of version numbers.
8711401Sandreas.sandberg@arm.com# E.g., compare_version((1,3,25), (1,4,1)')
885863Snate@binkert.org# returns -1, 0, 1 if v1 is <, ==, > v2
895863Snate@binkert.orgdef compare_versions(v1, v2):
904202Sbinkertn@umich.edu    def make_version_list(v):
915863Snate@binkert.org        if isinstance(v, (list,tuple)):
925863Snate@binkert.org            return v
935863Snate@binkert.org        elif isinstance(v, str):
945863Snate@binkert.org            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
95955SN/A        else:
966654Snate@binkert.org            raise TypeError
975273Sstever@gmail.com
985871Snate@binkert.org    v1 = make_version_list(v1)
995273Sstever@gmail.com    v2 = make_version_list(v2)
1006654Snate@binkert.org    # Compare corresponding elements of lists
1015396Ssaidi@eecs.umich.edu    for n1,n2 in zip(v1, v2):
1028120Sgblack@eecs.umich.edu        if n1 < n2: return -1
1038120Sgblack@eecs.umich.edu        if n1 > n2: return  1
1048120Sgblack@eecs.umich.edu    # all corresponding values are equal... see if one has extra values
1058120Sgblack@eecs.umich.edu    if len(v1) < len(v2): return -1
1068120Sgblack@eecs.umich.edu    if len(v1) > len(v2): return  1
1078120Sgblack@eecs.umich.edu    return 0
1088120Sgblack@eecs.umich.edu
1098120Sgblack@eecs.umich.edu# SCons version numbers need special processing because they can have
1108879Ssteve.reinhardt@amd.com# charecters and an release date embedded in them. This function does
1118879Ssteve.reinhardt@amd.com# the magic to extract them in a similar way to the SCons internal function
1128879Ssteve.reinhardt@amd.com# function does and then checks that the current version is not contained in
1138879Ssteve.reinhardt@amd.com# a list of version tuples (bad_ver_strs)
1148879Ssteve.reinhardt@amd.comdef CheckSCons(bad_ver_strs):
1158879Ssteve.reinhardt@amd.com    def scons_ver(v):
1168879Ssteve.reinhardt@amd.com        num_parts = v.split(' ')[0].split('.')
1178879Ssteve.reinhardt@amd.com        major = int(num_parts[0])
1188879Ssteve.reinhardt@amd.com        minor = int(re.match('\d+', num_parts[1]).group())
1198879Ssteve.reinhardt@amd.com        rev = 0
1208879Ssteve.reinhardt@amd.com        rdate = 0
1218879Ssteve.reinhardt@amd.com        if len(num_parts) > 2:
1228879Ssteve.reinhardt@amd.com            try: rev = int(re.match('\d+', num_parts[2]).group())
1238120Sgblack@eecs.umich.edu            except: pass
1248120Sgblack@eecs.umich.edu            rev_parts = num_parts[2].split('d')
1258120Sgblack@eecs.umich.edu            if len(rev_parts) > 1:
1268120Sgblack@eecs.umich.edu                rdate = int(re.match('\d+', rev_parts[1]).group())
1278120Sgblack@eecs.umich.edu
1288120Sgblack@eecs.umich.edu        return (major, minor, rev, rdate)
1298120Sgblack@eecs.umich.edu
1308120Sgblack@eecs.umich.edu    sc_ver = scons_ver(SCons.__version__)
1318120Sgblack@eecs.umich.edu    for bad_ver in bad_ver_strs:
1328120Sgblack@eecs.umich.edu        bv = (scons_ver(bad_ver[0]), scons_ver(bad_ver[1]))
1338120Sgblack@eecs.umich.edu        if  compare_versions(sc_ver, bv[0]) != -1 and\
1348120Sgblack@eecs.umich.edu            compare_versions(sc_ver, bv[1]) != 1:
1358120Sgblack@eecs.umich.edu            print "The version of SCons that you have installed: ", SCons.__version__
1368120Sgblack@eecs.umich.edu            print "has a bug that prevents it from working correctly with M5."
1378879Ssteve.reinhardt@amd.com            print "Please install a version NOT contained within the following",
1388879Ssteve.reinhardt@amd.com            print "ranges (inclusive):"
1398879Ssteve.reinhardt@amd.com            for bad_ver in bad_ver_strs:
1408879Ssteve.reinhardt@amd.com                print "    %s - %s" % bad_ver
14110458Sandreas.hansson@arm.com            Exit(2)
14210458Sandreas.hansson@arm.com
14310458Sandreas.hansson@arm.comCheckSCons(( 
1448879Ssteve.reinhardt@amd.com    # We need a version that is 0.96.91 or newer
1458879Ssteve.reinhardt@amd.com    ('0.0.0', '0.96.90'), 
1468879Ssteve.reinhardt@amd.com    ))
1478879Ssteve.reinhardt@amd.com
1489227Sandreas.hansson@arm.com
1499227Sandreas.hansson@arm.com# The absolute path to the current directory (where this file lives).
15012063Sgabeblack@google.comROOT = Dir('.').abspath
15112063Sgabeblack@google.com
15212063Sgabeblack@google.com# Path to the M5 source tree.
1538879Ssteve.reinhardt@amd.comSRCDIR = joinpath(ROOT, 'src')
1548879Ssteve.reinhardt@amd.com
1558879Ssteve.reinhardt@amd.com# tell python where to find m5 python code
1568879Ssteve.reinhardt@amd.comsys.path.append(joinpath(ROOT, 'src/python'))
15710453SAndrew.Bardsley@arm.com
15810453SAndrew.Bardsley@arm.comdef check_style_hook(ui):
15910453SAndrew.Bardsley@arm.com    ui.readconfig(joinpath(ROOT, '.hg', 'hgrc'))
16010456SCurtis.Dunham@arm.com    style_hook = ui.config('hooks', 'pretxncommit.style', None)
16110456SCurtis.Dunham@arm.com
16210456SCurtis.Dunham@arm.com    if not style_hook:
16310457Sandreas.hansson@arm.com        print """\
16410457Sandreas.hansson@arm.comYou're missing the M5 style hook.
16511342Sandreas.hansson@arm.comPlease install the hook so we can ensure that all code fits a common style.
16611342Sandreas.hansson@arm.com
1678120Sgblack@eecs.umich.eduAll you'd need to do is add the following lines to your repository .hg/hgrc
16812063Sgabeblack@google.comor your personal .hgrc
16912563Sgabeblack@google.com----------------
17012063Sgabeblack@google.com
17112063Sgabeblack@google.com[extensions]
1725871Snate@binkert.orgstyle = %s/util/style.py
1735871Snate@binkert.org
1746121Snate@binkert.org[hooks]
1755871Snate@binkert.orgpretxncommit.style = python:style.check_whitespace
1765871Snate@binkert.org""" % (ROOT)
1779926Sstan.czerniawski@arm.com        sys.exit(1)
17812243Sgabeblack@google.com
1791533SN/Aif ARGUMENTS.get('IGNORE_STYLE') != 'True' and isdir(joinpath(ROOT, '.hg')):
18012246Sgabeblack@google.com    try:
18112246Sgabeblack@google.com        from mercurial import ui
18212246Sgabeblack@google.com        check_style_hook(ui.ui())
18312246Sgabeblack@google.com    except ImportError:
1849239Sandreas.hansson@arm.com        pass
1859239Sandreas.hansson@arm.com
1869239Sandreas.hansson@arm.com###################################################
1879239Sandreas.hansson@arm.com#
18812563Sgabeblack@google.com# Figure out which configurations to set up based on the path(s) of
1899239Sandreas.hansson@arm.com# the target(s).
1909239Sandreas.hansson@arm.com#
191955SN/A###################################################
192955SN/A
1932632Sstever@eecs.umich.edu# Find default configuration & binary.
1942632Sstever@eecs.umich.eduDefault(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
195955SN/A
196955SN/A# helper function: find last occurrence of element in list
197955SN/Adef rfind(l, elt, offs = -1):
198955SN/A    for i in range(len(l)+offs, 0, -1):
1998878Ssteve.reinhardt@amd.com        if l[i] == elt:
200955SN/A            return i
2012632Sstever@eecs.umich.edu    raise ValueError, "element not found"
2022632Sstever@eecs.umich.edu
2032632Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2042632Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2052632Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2062632Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2072632Sstever@eecs.umich.edu# follow 'build' in the bulid path.
2088268Ssteve.reinhardt@amd.com
2098268Ssteve.reinhardt@amd.com# Generate absolute paths to targets so we can see where the build dir is
2108268Ssteve.reinhardt@amd.comif COMMAND_LINE_TARGETS:
2118268Ssteve.reinhardt@amd.com    # Ask SCons which directory it was invoked from
2128268Ssteve.reinhardt@amd.com    launch_dir = GetLaunchDir()
2138268Ssteve.reinhardt@amd.com    # Make targets relative to invocation directory
2148268Ssteve.reinhardt@amd.com    abs_targets = map(lambda x: os.path.normpath(joinpath(launch_dir, str(x))),
2152632Sstever@eecs.umich.edu                      COMMAND_LINE_TARGETS)
2162632Sstever@eecs.umich.eduelse:
2172632Sstever@eecs.umich.edu    # Default targets are relative to root of tree
2182632Sstever@eecs.umich.edu    abs_targets = map(lambda x: os.path.normpath(joinpath(ROOT, str(x))),
2198268Ssteve.reinhardt@amd.com                      DEFAULT_TARGETS)
2202632Sstever@eecs.umich.edu
2218268Ssteve.reinhardt@amd.com
2228268Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
2238268Ssteve.reinhardt@amd.com# collected targets reference.
2248268Ssteve.reinhardt@amd.combuild_paths = []
2253718Sstever@eecs.umich.edubuild_root = None
2262634Sstever@eecs.umich.edufor t in abs_targets:
2272634Sstever@eecs.umich.edu    path_dirs = t.split('/')
2285863Snate@binkert.org    try:
2292638Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
2308268Ssteve.reinhardt@amd.com    except:
2312632Sstever@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
2322632Sstever@eecs.umich.edu        Exit(1)
2332632Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2342632Sstever@eecs.umich.edu    if not build_root:
23512563Sgabeblack@google.com        build_root = this_build_root
2361858SN/A    else:
2373716Sstever@eecs.umich.edu        if this_build_root != build_root:
2382638Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
2392638Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
2402638Sstever@eecs.umich.edu            Exit(1)
2412638Sstever@eecs.umich.edu    build_path = joinpath('/',*path_dirs[:build_top+2])
24212563Sgabeblack@google.com    if build_path not in build_paths:
24312563Sgabeblack@google.com        build_paths.append(build_path)
2442638Sstever@eecs.umich.edu
2455863Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
2465863Snate@binkert.orgif not isdir(build_root):
2475863Snate@binkert.org    os.mkdir(build_root)
248955SN/A
2495341Sstever@gmail.com###################################################
2505341Sstever@gmail.com#
2515863Snate@binkert.org# Set up the default build environment.  This environment is copied
2527756SAli.Saidi@ARM.com# and modified according to each selected configuration.
2535341Sstever@gmail.com#
2546121Snate@binkert.org###################################################
2554494Ssaidi@eecs.umich.edu
2566121Snate@binkert.orgenv = Environment(ENV = os.environ,  # inherit user's environment vars
2571105SN/A                  ROOT = ROOT,
2582667Sstever@eecs.umich.edu                  SRCDIR = SRCDIR)
2592667Sstever@eecs.umich.edu
2602667Sstever@eecs.umich.eduExport('env')
2612667Sstever@eecs.umich.edu
2626121Snate@binkert.orgenv.SConsignFile(joinpath(build_root,"sconsign"))
2632667Sstever@eecs.umich.edu
2645341Sstever@gmail.com# Default duplicate option is to use hard links, but this messes up
2655863Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
2665341Sstever@gmail.com# file to file~ then copies to file, breaking the link.  Symbolic
2675341Sstever@gmail.com# (soft) links work better.
2685341Sstever@gmail.comenv.SetOption('duplicate', 'soft-copy')
2698120Sgblack@eecs.umich.edu
2705341Sstever@gmail.com# I waffle on this setting... it does avoid a few painful but
2718120Sgblack@eecs.umich.edu# unnecessary builds, but it also seems to make trivial builds take
2725341Sstever@gmail.com# noticeably longer.
2738120Sgblack@eecs.umich.eduif False:
2746121Snate@binkert.org    env.TargetSignatures('content')
2756121Snate@binkert.org
2769396Sandreas.hansson@arm.com#
2775397Ssaidi@eecs.umich.edu# Set up global sticky options... these are common to an entire build
2785397Ssaidi@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2797727SAli.Saidi@ARM.com#
2808268Ssteve.reinhardt@amd.com
2816168Snate@binkert.org# Option validators & converters for global sticky options
2825341Sstever@gmail.comdef PathListMakeAbsolute(val):
2838120Sgblack@eecs.umich.edu    if not val:
2848120Sgblack@eecs.umich.edu        return val
2858120Sgblack@eecs.umich.edu    f = lambda p: os.path.abspath(os.path.expanduser(p))
2866814Sgblack@eecs.umich.edu    return ':'.join(map(f, val.split(':')))
2875863Snate@binkert.org
2888120Sgblack@eecs.umich.edudef PathListAllExist(key, val, env):
2895341Sstever@gmail.com    if not val:
2905863Snate@binkert.org        return
2918268Ssteve.reinhardt@amd.com    paths = val.split(':')
2926121Snate@binkert.org    for path in paths:
2936121Snate@binkert.org        if not isdir(path):
2948268Ssteve.reinhardt@amd.com            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
2955742Snate@binkert.org
2965742Snate@binkert.orgglobal_sticky_opts_file = joinpath(build_root, 'options.global')
2975341Sstever@gmail.com
2985742Snate@binkert.orgglobal_sticky_opts = Options(global_sticky_opts_file, args=ARGUMENTS)
2995742Snate@binkert.org
3005341Sstever@gmail.comglobal_sticky_opts.AddOptions(
3016017Snate@binkert.org    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
3026121Snate@binkert.org    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
3036017Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
30412158Sandreas.sandberg@arm.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
30512158Sandreas.sandberg@arm.com    ('EXTRAS', 'Add Extra directories to the compilation', '',
30612158Sandreas.sandberg@arm.com     PathListAllExist, PathListMakeAbsolute)
3078120Sgblack@eecs.umich.edu    )    
3087756SAli.Saidi@ARM.com
3097756SAli.Saidi@ARM.com
3107756SAli.Saidi@ARM.com# base help text
3117756SAli.Saidi@ARM.comhelp_text = '''
3127816Ssteve.reinhardt@amd.comUsage: scons [scons options] [build options] [target(s)]
3137816Ssteve.reinhardt@amd.com
3147816Ssteve.reinhardt@amd.com'''
3157816Ssteve.reinhardt@amd.com
3167816Ssteve.reinhardt@amd.comhelp_text += "Global sticky options:\n" \
31711979Sgabeblack@google.com             + global_sticky_opts.GenerateHelpText(env)
3187816Ssteve.reinhardt@amd.com
3197816Ssteve.reinhardt@amd.com# Update env with values from ARGUMENTS & file global_sticky_opts_file
3207816Ssteve.reinhardt@amd.comglobal_sticky_opts.Update(env)
3217816Ssteve.reinhardt@amd.com
3227756SAli.Saidi@ARM.com# Save sticky option settings back to current options file
3237756SAli.Saidi@ARM.comglobal_sticky_opts.Save(global_sticky_opts_file, env)
3249227Sandreas.hansson@arm.com
3259227Sandreas.hansson@arm.com# Parse EXTRAS option to build list of all directories where we're
3269227Sandreas.hansson@arm.com# look for sources etc.  This list is exported as base_dir_list.
3279227Sandreas.hansson@arm.combase_dir = joinpath(ROOT, 'src')
3289590Sandreas@sandberg.pp.seif env['EXTRAS']:
3299590Sandreas@sandberg.pp.se    extras_dir_list = env['EXTRAS'].split(':')
3309590Sandreas@sandberg.pp.seelse:
3319590Sandreas@sandberg.pp.se    extras_dir_list = []
3329590Sandreas@sandberg.pp.se
3339590Sandreas@sandberg.pp.seExport('base_dir')
3346654Snate@binkert.orgExport('extras_dir_list')
3356654Snate@binkert.org
3365871Snate@binkert.org# M5_PLY is used by isa_parser.py to find the PLY package.
3376121Snate@binkert.orgenv.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
3388946Sandreas.hansson@arm.comenv['GCC'] = subprocess.Popen(env['CXX'] + ' --version', shell=True,
3399419Sandreas.hansson@arm.com        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
34012563Sgabeblack@google.com        close_fds=True).communicate()[0].find('g++') >= 0
3413918Ssaidi@eecs.umich.eduenv['SUNCC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
3423918Ssaidi@eecs.umich.edu        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
3431858SN/A        close_fds=True).communicate()[0].find('Sun C++') >= 0
3449556Sandreas.hansson@arm.comenv['ICC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
3459556Sandreas.hansson@arm.com        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
3469556Sandreas.hansson@arm.com        close_fds=True).communicate()[0].find('Intel') >= 0
3479556Sandreas.hansson@arm.comif env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
34811294Sandreas.hansson@arm.com    print 'Error: How can we have two at the same time?'
34911294Sandreas.hansson@arm.com    Exit(1)
35011294Sandreas.hansson@arm.com
35111294Sandreas.hansson@arm.com
35210878Sandreas.hansson@arm.com# Set up default C++ compiler flags
35310878Sandreas.hansson@arm.comif env['GCC']:
35411811Sbaz21@cam.ac.uk    env.Append(CCFLAGS='-pipe')
35511811Sbaz21@cam.ac.uk    env.Append(CCFLAGS='-fno-strict-aliasing')
35611811Sbaz21@cam.ac.uk    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
35711982Sgabeblack@google.com    env.Append(CXXFLAGS='-Wno-deprecated')
35811982Sgabeblack@google.comelif env['ICC']:
35911982Sgabeblack@google.com    pass #Fix me... add warning flags once we clean up icc warnings
36011982Sgabeblack@google.comelif env['SUNCC']:
36111992Sgabeblack@google.com    env.Append(CCFLAGS='-Qoption ccfe')
36211982Sgabeblack@google.com    env.Append(CCFLAGS='-features=gcc')
36311982Sgabeblack@google.com    env.Append(CCFLAGS='-features=extensions')
36412305Sgabeblack@google.com    env.Append(CCFLAGS='-library=stlport4')
36512305Sgabeblack@google.com    env.Append(CCFLAGS='-xar')
36612305Sgabeblack@google.com#    env.Append(CCFLAGS='-instances=semiexplicit')
36712305Sgabeblack@google.comelse:
36812305Sgabeblack@google.com    print 'Error: Don\'t know what compiler options to use for your compiler.'
36912305Sgabeblack@google.com    print '       Please fix SConstruct and src/SConscript and try again.'
37012305Sgabeblack@google.com    Exit(1)
3719556Sandreas.hansson@arm.com
37212563Sgabeblack@google.com# Do this after we save setting back, or else we'll tack on an
37312563Sgabeblack@google.com# extra 'qdo' every time we run scons.
37412563Sgabeblack@google.comif env['BATCH']:
37512563Sgabeblack@google.com    env['CC']     = env['BATCH_CMD'] + ' ' + env['CC']
3769556Sandreas.hansson@arm.com    env['CXX']    = env['BATCH_CMD'] + ' ' + env['CXX']
37712563Sgabeblack@google.com    env['AS']     = env['BATCH_CMD'] + ' ' + env['AS']
37812563Sgabeblack@google.com    env['AR']     = env['BATCH_CMD'] + ' ' + env['AR']
3799556Sandreas.hansson@arm.com    env['RANLIB'] = env['BATCH_CMD'] + ' ' + env['RANLIB']
38012563Sgabeblack@google.com
38112563Sgabeblack@google.comif sys.platform == 'cygwin':
38212563Sgabeblack@google.com    # cygwin has some header file issues...
38312563Sgabeblack@google.com    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
38412563Sgabeblack@google.comenv.Append(CPPPATH=[Dir('ext/dnet')])
38512563Sgabeblack@google.com
38612563Sgabeblack@google.com# Check for SWIG
38712563Sgabeblack@google.comif not env.has_key('SWIG'):
3889556Sandreas.hansson@arm.com    print 'Error: SWIG utility not found.'
3899556Sandreas.hansson@arm.com    print '       Please install (see http://www.swig.org) and retry.'
3906121Snate@binkert.org    Exit(1)
39111500Sandreas.hansson@arm.com
39210238Sandreas.hansson@arm.com# Check for appropriate SWIG version
39310878Sandreas.hansson@arm.comswig_version = os.popen('swig -version').read().split()
3949420Sandreas.hansson@arm.com# First 3 words should be "SWIG Version x.y.z"
39511500Sandreas.hansson@arm.comif len(swig_version) < 3 or \
39612563Sgabeblack@google.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
39712563Sgabeblack@google.com    print 'Error determining SWIG version.'
3989420Sandreas.hansson@arm.com    Exit(1)
3999420Sandreas.hansson@arm.com
4009420Sandreas.hansson@arm.commin_swig_version = '1.3.28'
4019420Sandreas.hansson@arm.comif compare_versions(swig_version[2], min_swig_version) < 0:
40212063Sgabeblack@google.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
40312063Sgabeblack@google.com    print '       Installed version:', swig_version[2]
40412063Sgabeblack@google.com    Exit(1)
40512063Sgabeblack@google.com
40612063Sgabeblack@google.com# Set up SWIG flags & scanner
40712063Sgabeblack@google.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
40812063Sgabeblack@google.comenv.Append(SWIGFLAGS=swig_flags)
40912063Sgabeblack@google.com
41012063Sgabeblack@google.com# filter out all existing swig scanners, they mess up the dependency
41112063Sgabeblack@google.com# stuff for some reason
41212063Sgabeblack@google.comscanners = []
41312063Sgabeblack@google.comfor scanner in env['SCANNERS']:
41412063Sgabeblack@google.com    skeys = scanner.skeys
41512063Sgabeblack@google.com    if skeys == '.i':
41612063Sgabeblack@google.com        continue
41712063Sgabeblack@google.com
41812063Sgabeblack@google.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
41912063Sgabeblack@google.com        continue
42012063Sgabeblack@google.com
42112063Sgabeblack@google.com    scanners.append(scanner)
42212063Sgabeblack@google.com
42312063Sgabeblack@google.com# add the new swig scanner that we like better
42410264Sandreas.hansson@arm.comfrom SCons.Scanner import ClassicCPP as CPPScanner
42510264Sandreas.hansson@arm.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
42610264Sandreas.hansson@arm.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
42710264Sandreas.hansson@arm.com
42811925Sgabeblack@google.com# replace the scanners list that has what we want
42911925Sgabeblack@google.comenv['SCANNERS'] = scanners
43011500Sandreas.hansson@arm.com
43110264Sandreas.hansson@arm.com# Add a custom Check function to the Configure context so that we can
43211500Sandreas.hansson@arm.com# figure out if the compiler adds leading underscores to global
43311500Sandreas.hansson@arm.com# variables.  This is needed for the autogenerated asm files that we
43411500Sandreas.hansson@arm.com# use for embedding the python code.
43511500Sandreas.hansson@arm.comdef CheckLeading(context):
43610866Sandreas.hansson@arm.com    context.Message("Checking for leading underscore in global variables...")
43711500Sandreas.hansson@arm.com    # 1) Define a global variable called x from asm so the C compiler
43812563Sgabeblack@google.com    #    won't change the symbol at all.
43912563Sgabeblack@google.com    # 2) Declare that variable.
44012563Sgabeblack@google.com    # 3) Use the variable
44112563Sgabeblack@google.com    #
44212563Sgabeblack@google.com    # If the compiler prepends an underscore, this will successfully
44312563Sgabeblack@google.com    # link because the external symbol 'x' will be called '_x' which
44410264Sandreas.hansson@arm.com    # was defined by the asm statement.  If the compiler does not
44510457Sandreas.hansson@arm.com    # prepend an underscore, this will not successfully link because
44610457Sandreas.hansson@arm.com    # '_x' will have been defined by assembly, while the C portion of
44710457Sandreas.hansson@arm.com    # the code will be trying to use 'x'
44810457Sandreas.hansson@arm.com    ret = context.TryLink('''
44910457Sandreas.hansson@arm.com        asm(".globl _x; _x: .byte 0");
45012563Sgabeblack@google.com        extern int x;
45112563Sgabeblack@google.com        int main() { return x; }
45212563Sgabeblack@google.com        ''', extension=".c")
45310457Sandreas.hansson@arm.com    context.env.Append(LEADING_UNDERSCORE=ret)
45412063Sgabeblack@google.com    context.Result(ret)
45512063Sgabeblack@google.com    return ret
45612063Sgabeblack@google.com
45712563Sgabeblack@google.com# Platform-specific configuration.  Note again that we assume that all
45812563Sgabeblack@google.com# builds under a given build root run on the same host platform.
45912563Sgabeblack@google.comconf = Configure(env,
46012563Sgabeblack@google.com                 conf_dir = joinpath(build_root, '.scons_config'),
46112563Sgabeblack@google.com                 log_file = joinpath(build_root, 'scons_config.log'),
46212563Sgabeblack@google.com                 custom_tests = { 'CheckLeading' : CheckLeading })
46312063Sgabeblack@google.com
46412063Sgabeblack@google.com# Check for leading underscores.  Don't really need to worry either
46510238Sandreas.hansson@arm.com# way so don't need to check the return code.
46610238Sandreas.hansson@arm.comconf.CheckLeading()
46710238Sandreas.hansson@arm.com
46812063Sgabeblack@google.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
46910238Sandreas.hansson@arm.comtry:
47010238Sandreas.hansson@arm.com    import platform
47110416Sandreas.hansson@arm.com    uname = platform.uname()
47210238Sandreas.hansson@arm.com    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
4739227Sandreas.hansson@arm.com        if int(subprocess.Popen('sysctl -n hw.cpu64bit_capable', shell=True,
47410238Sandreas.hansson@arm.com               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
47510416Sandreas.hansson@arm.com               close_fds=True).communicate()[0][0]):
47610416Sandreas.hansson@arm.com            env.Append(CCFLAGS='-arch x86_64')
4779227Sandreas.hansson@arm.com            env.Append(CFLAGS='-arch x86_64')
4789590Sandreas@sandberg.pp.se            env.Append(LINKFLAGS='-arch x86_64')
4799590Sandreas@sandberg.pp.se            env.Append(ASFLAGS='-arch x86_64')
4809590Sandreas@sandberg.pp.seexcept:
48112304Sgabeblack@google.com    pass
48212304Sgabeblack@google.com
48312304Sgabeblack@google.com# Recent versions of scons substitute a "Null" object for Configure()
48412688Sgiacomo.travaglini@arm.com# when configuration isn't necessary, e.g., if the "--help" option is
48512688Sgiacomo.travaglini@arm.com# present.  Unfortuantely this Null object always returns false,
48612688Sgiacomo.travaglini@arm.com# breaking all our configuration checks.  We replace it with our own
48712304Sgabeblack@google.com# more optimistic null object that returns True instead.
48812304Sgabeblack@google.comif not conf:
48912688Sgiacomo.travaglini@arm.com    def NullCheck(*args, **kwargs):
49012688Sgiacomo.travaglini@arm.com        return True
49112304Sgabeblack@google.com
49212304Sgabeblack@google.com    class NullConf:
49312304Sgabeblack@google.com        def __init__(self, env):
49412304Sgabeblack@google.com            self.env = env
49512304Sgabeblack@google.com        def Finish(self):
49612688Sgiacomo.travaglini@arm.com            return self.env
49712688Sgiacomo.travaglini@arm.com        def __getattr__(self, mname):
49812688Sgiacomo.travaglini@arm.com            return NullCheck
49912304Sgabeblack@google.com
5008737Skoansin.tan@gmail.com    conf = NullConf(env)
50110878Sandreas.hansson@arm.com
50211500Sandreas.hansson@arm.com# Find Python include and library directories for embedding the
5039420Sandreas.hansson@arm.com# interpreter.  For consistency, we will use the same Python
5048737Skoansin.tan@gmail.com# installation used to run scons (and thus this script).  If you want
50510106SMitch.Hayenga@arm.com# to link in an alternate version, see above for instructions on how
5068737Skoansin.tan@gmail.com# to invoke scons with a different copy of the Python interpreter.
5078737Skoansin.tan@gmail.com
50810878Sandreas.hansson@arm.com# Get brief Python version name (e.g., "python2.4") for locating
50912563Sgabeblack@google.com# include & library files
51012563Sgabeblack@google.compy_version_name = 'python' + sys.version[:3]
5118737Skoansin.tan@gmail.com
5128737Skoansin.tan@gmail.com# include path, e.g. /usr/local/include/python2.4
51312563Sgabeblack@google.compy_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
5148737Skoansin.tan@gmail.comenv.Append(CPPPATH = py_header_path)
5158737Skoansin.tan@gmail.com# verify that it works
51611294Sandreas.hansson@arm.comif not conf.CheckHeader('Python.h', '<>'):
5179556Sandreas.hansson@arm.com    print "Error: can't find Python.h header in", py_header_path
5189556Sandreas.hansson@arm.com    Exit(1)
5199556Sandreas.hansson@arm.com
52011294Sandreas.hansson@arm.com# add library path too if it's not in the default place
52110278SAndreas.Sandberg@ARM.compy_lib_path = None
52210278SAndreas.Sandberg@ARM.comif sys.exec_prefix != '/usr':
52310278SAndreas.Sandberg@ARM.com    py_lib_path = joinpath(sys.exec_prefix, 'lib')
52410278SAndreas.Sandberg@ARM.comelif sys.platform == 'cygwin':
52510278SAndreas.Sandberg@ARM.com    # cygwin puts the .dll in /bin for some reason
52610278SAndreas.Sandberg@ARM.com    py_lib_path = '/bin'
5279556Sandreas.hansson@arm.comif py_lib_path:
5289590Sandreas@sandberg.pp.se    env.Append(LIBPATH = py_lib_path)
5299590Sandreas@sandberg.pp.se    print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
5309420Sandreas.hansson@arm.comif not conf.CheckLib(py_version_name):
5319846Sandreas.hansson@arm.com    print "Error: can't find Python library", py_version_name
5329846Sandreas.hansson@arm.com    Exit(1)
5339846Sandreas.hansson@arm.com
5349846Sandreas.hansson@arm.com# On Solaris you need to use libsocket for socket ops
5358946Sandreas.hansson@arm.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
53611811Sbaz21@cam.ac.uk   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
53711811Sbaz21@cam.ac.uk       print "Can't find library with socket calls (e.g. accept())"
53811811Sbaz21@cam.ac.uk       Exit(1)
53911811Sbaz21@cam.ac.uk
54012304Sgabeblack@google.com# Check for zlib.  If the check passes, libz will be automatically
54112304Sgabeblack@google.com# added to the LIBS environment variable.
54212304Sgabeblack@google.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
54312304Sgabeblack@google.com    print 'Error: did not find needed zlib compression library '\
54412304Sgabeblack@google.com          'and/or zlib.h header file.'
54512304Sgabeblack@google.com    print '       Please install zlib and try again.'
54612304Sgabeblack@google.com    Exit(1)
54712304Sgabeblack@google.com
54812304Sgabeblack@google.com# Check for <fenv.h> (C99 FP environment control)
54912304Sgabeblack@google.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
55012304Sgabeblack@google.comif not have_fenv:
55112304Sgabeblack@google.com    print "Warning: Header file <fenv.h> not found."
55212304Sgabeblack@google.com    print "         This host has no IEEE FP rounding mode control."
55312304Sgabeblack@google.com
55412304Sgabeblack@google.com# Check for mysql.
55512304Sgabeblack@google.commysql_config = WhereIs('mysql_config')
5563918Ssaidi@eecs.umich.eduhave_mysql = mysql_config != None
55712563Sgabeblack@google.com
55812563Sgabeblack@google.com# Check MySQL version.
55912563Sgabeblack@google.comif have_mysql:
56012563Sgabeblack@google.com    mysql_version = os.popen(mysql_config + ' --version').read()
5619068SAli.Saidi@ARM.com    min_mysql_version = '4.1'
56212563Sgabeblack@google.com    if compare_versions(mysql_version, min_mysql_version) < 0:
56312563Sgabeblack@google.com        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
5649068SAli.Saidi@ARM.com        print '         Version', mysql_version, 'detected.'
56512563Sgabeblack@google.com        have_mysql = False
56612563Sgabeblack@google.com
56712563Sgabeblack@google.com# Set up mysql_config commands.
56812563Sgabeblack@google.comif have_mysql:
56912563Sgabeblack@google.com    mysql_config_include = mysql_config + ' --include'
57012563Sgabeblack@google.com    if os.system(mysql_config_include + ' > /dev/null') != 0:
57112563Sgabeblack@google.com        # older mysql_config versions don't support --include, use
57212563Sgabeblack@google.com        # --cflags instead
5733918Ssaidi@eecs.umich.edu        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
5743918Ssaidi@eecs.umich.edu    # This seems to work in all versions
5756157Snate@binkert.org    mysql_config_libs = mysql_config + ' --libs'
5766157Snate@binkert.org
5776157Snate@binkert.orgenv = conf.Finish()
5786157Snate@binkert.org
5795397Ssaidi@eecs.umich.edu# Define the universe of supported ISAs
5805397Ssaidi@eecs.umich.eduall_isa_list = [ ]
5816121Snate@binkert.orgExport('all_isa_list')
5826121Snate@binkert.org
5836121Snate@binkert.org# Define the universe of supported CPU models
5846121Snate@binkert.orgall_cpu_list = [ ]
5856121Snate@binkert.orgdefault_cpus = [ ]
5866121Snate@binkert.orgExport('all_cpu_list', 'default_cpus')
5875397Ssaidi@eecs.umich.edu
5881851SN/A# Sticky options get saved in the options file so they persist from
5891851SN/A# one invocation to the next (unless overridden, in which case the new
5907739Sgblack@eecs.umich.edu# value becomes sticky).
591955SN/Asticky_opts = Options(args=ARGUMENTS)
5929396Sandreas.hansson@arm.comExport('sticky_opts')
5939396Sandreas.hansson@arm.com
5949396Sandreas.hansson@arm.com# Non-sticky options only apply to the current build.
5959396Sandreas.hansson@arm.comnonsticky_opts = Options(args=ARGUMENTS)
5969396Sandreas.hansson@arm.comExport('nonsticky_opts')
5979396Sandreas.hansson@arm.com
59812563Sgabeblack@google.com# Walk the tree and execute all SConsopts scripts that wil add to the
59912563Sgabeblack@google.com# above options
60012563Sgabeblack@google.comfor bdir in [ base_dir ] + extras_dir_list:
60112563Sgabeblack@google.com    for root, dirs, files in os.walk(bdir):
6029396Sandreas.hansson@arm.com        if 'SConsopts' in files:
6039396Sandreas.hansson@arm.com            print "Reading", joinpath(root, 'SConsopts')
6049396Sandreas.hansson@arm.com            SConscript(joinpath(root, 'SConsopts'))
6059396Sandreas.hansson@arm.com
6069396Sandreas.hansson@arm.comall_isa_list.sort()
6079396Sandreas.hansson@arm.comall_cpu_list.sort()
60812563Sgabeblack@google.comdefault_cpus.sort()
60912563Sgabeblack@google.com
61012563Sgabeblack@google.comsticky_opts.AddOptions(
61112563Sgabeblack@google.com    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
61212563Sgabeblack@google.com    BoolOption('FULL_SYSTEM', 'Full-system support', False),
6139477Sandreas.hansson@arm.com    # There's a bug in scons 0.96.1 that causes ListOptions with list
6149477Sandreas.hansson@arm.com    # values (more than one value) not to be able to be restored from
6159477Sandreas.hansson@arm.com    # a saved option file.  If this causes trouble then upgrade to
6169477Sandreas.hansson@arm.com    # scons 0.96.90 or later.
6179477Sandreas.hansson@arm.com    ListOption('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
6189477Sandreas.hansson@arm.com    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
6199477Sandreas.hansson@arm.com    BoolOption('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
6209477Sandreas.hansson@arm.com               False),
6219477Sandreas.hansson@arm.com    BoolOption('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
6229477Sandreas.hansson@arm.com               False),
6239477Sandreas.hansson@arm.com    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
6249477Sandreas.hansson@arm.com               False),
6259477Sandreas.hansson@arm.com    BoolOption('SS_COMPATIBLE_FP',
6269477Sandreas.hansson@arm.com               'Make floating-point results compatible with SimpleScalar',
62712563Sgabeblack@google.com               False),
62812563Sgabeblack@google.com    BoolOption('USE_SSE2',
62912563Sgabeblack@google.com               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
6309396Sandreas.hansson@arm.com               False),
6312667Sstever@eecs.umich.edu    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
63210710Sandreas.hansson@arm.com    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
63310710Sandreas.hansson@arm.com    BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
63410710Sandreas.hansson@arm.com    )
63511811Sbaz21@cam.ac.uk
63611811Sbaz21@cam.ac.uknonsticky_opts.AddOptions(
63711811Sbaz21@cam.ac.uk    BoolOption('update_ref', 'Update test reference outputs', False)
63811811Sbaz21@cam.ac.uk    )
63911811Sbaz21@cam.ac.uk
64011811Sbaz21@cam.ac.uk# These options get exported to #defines in config/*.hh (see src/SConscript).
64110710Sandreas.hansson@arm.comenv.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
64210710Sandreas.hansson@arm.com                     'USE_MYSQL', 'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', \
64310710Sandreas.hansson@arm.com                     'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', \
64410710Sandreas.hansson@arm.com                     'USE_CHECKER', 'TARGET_ISA']
64510384SCurtis.Dunham@arm.com
6469986Sandreas@sandberg.pp.se# Define a handy 'no-op' action
6479986Sandreas@sandberg.pp.sedef no_action(target, source, env):
6489986Sandreas@sandberg.pp.se    return 0
6499986Sandreas@sandberg.pp.se
6509986Sandreas@sandberg.pp.seenv.NoAction = Action(no_action, None)
6519986Sandreas@sandberg.pp.se
6529986Sandreas@sandberg.pp.se###################################################
6539986Sandreas@sandberg.pp.se#
6549986Sandreas@sandberg.pp.se# Define a SCons builder for configuration flag headers.
6559986Sandreas@sandberg.pp.se#
6569986Sandreas@sandberg.pp.se###################################################
6579986Sandreas@sandberg.pp.se
6589986Sandreas@sandberg.pp.se# This function generates a config header file that #defines the
6599986Sandreas@sandberg.pp.se# option symbol to the current option setting (0 or 1).  The source
6609986Sandreas@sandberg.pp.se# operands are the name of the option and a Value node containing the
6619986Sandreas@sandberg.pp.se# value of the option.
6629986Sandreas@sandberg.pp.sedef build_config_file(target, source, env):
6639986Sandreas@sandberg.pp.se    (option, value) = [s.get_contents() for s in source]
6649986Sandreas@sandberg.pp.se    f = file(str(target[0]), 'w')
6659986Sandreas@sandberg.pp.se    print >> f, '#define', option, value
6662638Sstever@eecs.umich.edu    f.close()
6672638Sstever@eecs.umich.edu    return None
6686121Snate@binkert.org
6693716Sstever@eecs.umich.edu# Generate the message to be printed when building the config file.
6705522Snate@binkert.orgdef build_config_file_string(target, source, env):
6719986Sandreas@sandberg.pp.se    (option, value) = [s.get_contents() for s in source]
6729986Sandreas@sandberg.pp.se    return "Defining %s as %s in %s." % (option, value, target[0])
6739986Sandreas@sandberg.pp.se
6745522Snate@binkert.org# Combine the two functions into a scons Action object.
6755227Ssaidi@eecs.umich.educonfig_action = Action(build_config_file, build_config_file_string)
6765227Ssaidi@eecs.umich.edu
6775227Ssaidi@eecs.umich.edu# The emitter munges the source & target node lists to reflect what
6785227Ssaidi@eecs.umich.edu# we're really doing.
6796654Snate@binkert.orgdef config_emitter(target, source, env):
6806654Snate@binkert.org    # extract option name from Builder arg
6817769SAli.Saidi@ARM.com    option = str(target[0])
6827769SAli.Saidi@ARM.com    # True target is config header file
6837769SAli.Saidi@ARM.com    target = joinpath('config', option.lower() + '.hh')
6847769SAli.Saidi@ARM.com    val = env[option]
6855227Ssaidi@eecs.umich.edu    if isinstance(val, bool):
6865227Ssaidi@eecs.umich.edu        # Force value to 0/1
6875227Ssaidi@eecs.umich.edu        val = int(val)
6885204Sstever@gmail.com    elif isinstance(val, str):
6895204Sstever@gmail.com        val = '"' + val + '"'
6905204Sstever@gmail.com
6915204Sstever@gmail.com    # Sources are option name & value (packaged in SCons Value nodes)
6925204Sstever@gmail.com    return ([target], [Value(option), Value(val)])
6935204Sstever@gmail.com
6945204Sstever@gmail.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
6955204Sstever@gmail.com
6965204Sstever@gmail.comenv.Append(BUILDERS = { 'ConfigFile' : config_builder })
6975204Sstever@gmail.com
6985204Sstever@gmail.com###################################################
6995204Sstever@gmail.com#
7005204Sstever@gmail.com# Define a SCons builder for copying files.  This is used by the
7015204Sstever@gmail.com# Python zipfile code in src/python/SConscript, but is placed up here
7025204Sstever@gmail.com# since it's potentially more generally applicable.
7035204Sstever@gmail.com#
7045204Sstever@gmail.com###################################################
7056121Snate@binkert.org
7065204Sstever@gmail.comcopy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
7077727SAli.Saidi@ARM.com
7087727SAli.Saidi@ARM.comenv.Append(BUILDERS = { 'CopyFile' : copy_builder })
70912563Sgabeblack@google.com
7107727SAli.Saidi@ARM.com###################################################
7117727SAli.Saidi@ARM.com#
71211988Sandreas.sandberg@arm.com# Define a simple SCons builder to concatenate files.
71311988Sandreas.sandberg@arm.com#
71410453SAndrew.Bardsley@arm.com# Used to append the Python zip archive to the executable.
71510453SAndrew.Bardsley@arm.com#
71610453SAndrew.Bardsley@arm.com###################################################
71710453SAndrew.Bardsley@arm.com
71810453SAndrew.Bardsley@arm.comconcat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
71910453SAndrew.Bardsley@arm.com                                          'chmod +x $TARGET']))
72010453SAndrew.Bardsley@arm.com
72110453SAndrew.Bardsley@arm.comenv.Append(BUILDERS = { 'Concat' : concat_builder })
72210453SAndrew.Bardsley@arm.com
72310453SAndrew.Bardsley@arm.com
72410160Sandreas.hansson@arm.com# libelf build is shared across all configs in the build root.
72510453SAndrew.Bardsley@arm.comenv.SConscript('ext/libelf/SConscript',
72610453SAndrew.Bardsley@arm.com               build_dir = joinpath(build_root, 'libelf'),
72710453SAndrew.Bardsley@arm.com               exports = 'env')
72810453SAndrew.Bardsley@arm.com
72910453SAndrew.Bardsley@arm.com###################################################
73010453SAndrew.Bardsley@arm.com#
73110453SAndrew.Bardsley@arm.com# This function is used to set up a directory with switching headers
73210453SAndrew.Bardsley@arm.com#
7339812Sandreas.hansson@arm.com###################################################
73410453SAndrew.Bardsley@arm.com
73510453SAndrew.Bardsley@arm.comenv['ALL_ISA_LIST'] = all_isa_list
73610453SAndrew.Bardsley@arm.comdef make_switching_dir(dirname, switch_headers, env):
73710453SAndrew.Bardsley@arm.com    # Generate the header.  target[0] is the full path of the output
73810453SAndrew.Bardsley@arm.com    # header to generate.  'source' is a dummy variable, since we get the
73910453SAndrew.Bardsley@arm.com    # list of ISAs from env['ALL_ISA_LIST'].
74010453SAndrew.Bardsley@arm.com    def gen_switch_hdr(target, source, env):
74110453SAndrew.Bardsley@arm.com        fname = str(target[0])
74210453SAndrew.Bardsley@arm.com        basename = os.path.basename(fname)
74310453SAndrew.Bardsley@arm.com        f = open(fname, 'w')
74410453SAndrew.Bardsley@arm.com        f.write('#include "arch/isa_specific.hh"\n')
74510453SAndrew.Bardsley@arm.com        cond = '#if'
7467727SAli.Saidi@ARM.com        for isa in all_isa_list:
74710453SAndrew.Bardsley@arm.com            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
74810453SAndrew.Bardsley@arm.com                    % (cond, isa.upper(), dirname, isa, basename))
74912563Sgabeblack@google.com            cond = '#elif'
75012563Sgabeblack@google.com        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
75112563Sgabeblack@google.com        f.close()
75210453SAndrew.Bardsley@arm.com        return 0
7533118Sstever@eecs.umich.edu
75410453SAndrew.Bardsley@arm.com    # String to print when generating header
75510453SAndrew.Bardsley@arm.com    def gen_switch_hdr_string(target, source, env):
75612563Sgabeblack@google.com        return "Generating switch header " + str(target[0])
75710453SAndrew.Bardsley@arm.com
7583118Sstever@eecs.umich.edu    # Build SCons Action object. 'varlist' specifies env vars that this
7593483Ssaidi@eecs.umich.edu    # action depends on; when env['ALL_ISA_LIST'] changes these actions
7603494Ssaidi@eecs.umich.edu    # should get re-executed.
7613494Ssaidi@eecs.umich.edu    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
76212563Sgabeblack@google.com                               varlist=['ALL_ISA_LIST'])
7633483Ssaidi@eecs.umich.edu
7643483Ssaidi@eecs.umich.edu    # Instantiate actions for each header
7653053Sstever@eecs.umich.edu    for hdr in switch_headers:
7663053Sstever@eecs.umich.edu        env.Command(hdr, [], switch_hdr_action)
7673918Ssaidi@eecs.umich.eduExport('make_switching_dir')
76812563Sgabeblack@google.com
76912563Sgabeblack@google.com###################################################
77012563Sgabeblack@google.com#
7713053Sstever@eecs.umich.edu# Define build environments for selected configurations.
7723053Sstever@eecs.umich.edu#
7739396Sandreas.hansson@arm.com###################################################
7749396Sandreas.hansson@arm.com
7759396Sandreas.hansson@arm.com# rename base env
7769396Sandreas.hansson@arm.combase_env = env
7779396Sandreas.hansson@arm.com
7789396Sandreas.hansson@arm.comfor build_path in build_paths:
7799396Sandreas.hansson@arm.com    print "Building in", build_path
7809396Sandreas.hansson@arm.com
7819396Sandreas.hansson@arm.com    # Make a copy of the build-root environment to use for this config.
7829477Sandreas.hansson@arm.com    env = base_env.Copy()
7839396Sandreas.hansson@arm.com    env['BUILDDIR'] = build_path
78412563Sgabeblack@google.com
78512563Sgabeblack@google.com    # build_dir is the tail component of build path, and is used to
78612563Sgabeblack@google.com    # determine the build parameters (e.g., 'ALPHA_SE')
78712563Sgabeblack@google.com    (build_root, build_dir) = os.path.split(build_path)
7889396Sandreas.hansson@arm.com
7897840Snate@binkert.org    # Set env options according to the build directory config.
7907865Sgblack@eecs.umich.edu    sticky_opts.files = []
7917865Sgblack@eecs.umich.edu    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
7927865Sgblack@eecs.umich.edu    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
7937865Sgblack@eecs.umich.edu    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
7947865Sgblack@eecs.umich.edu    current_opts_file = joinpath(build_root, 'options', build_dir)
7957840Snate@binkert.org    if isfile(current_opts_file):
7969900Sandreas@sandberg.pp.se        sticky_opts.files.append(current_opts_file)
7979900Sandreas@sandberg.pp.se        print "Using saved options file %s" % current_opts_file
7989900Sandreas@sandberg.pp.se    else:
7999900Sandreas@sandberg.pp.se        # Build dir-specific options file doesn't exist.
80010456SCurtis.Dunham@arm.com
80110456SCurtis.Dunham@arm.com        # Make sure the directory is there so we can create it later
80210456SCurtis.Dunham@arm.com        opt_dir = os.path.dirname(current_opts_file)
80310456SCurtis.Dunham@arm.com        if not isdir(opt_dir):
80410456SCurtis.Dunham@arm.com            os.mkdir(opt_dir)
80510456SCurtis.Dunham@arm.com
80612563Sgabeblack@google.com        # Get default build options from source tree.  Options are
80712563Sgabeblack@google.com        # normally determined by name of $BUILD_DIR, but can be
80812563Sgabeblack@google.com        # overriden by 'default=' arg on command line.
80912563Sgabeblack@google.com        default_opts_file = joinpath('build_opts',
8109045SAli.Saidi@ARM.com                                     ARGUMENTS.get('default', build_dir))
81111235Sandreas.sandberg@arm.com        if isfile(default_opts_file):
81211235Sandreas.sandberg@arm.com            sticky_opts.files.append(default_opts_file)
81311235Sandreas.sandberg@arm.com            print "Options file %s not found,\n  using defaults in %s" \
81411235Sandreas.sandberg@arm.com                  % (current_opts_file, default_opts_file)
81511235Sandreas.sandberg@arm.com        else:
81612485Sjang.hanhwi@gmail.com            print "Error: cannot find options file %s or %s" \
81712485Sjang.hanhwi@gmail.com                  % (current_opts_file, default_opts_file)
81812485Sjang.hanhwi@gmail.com            Exit(1)
81911235Sandreas.sandberg@arm.com
82011811Sbaz21@cam.ac.uk    # Apply current option settings to env
82112485Sjang.hanhwi@gmail.com    sticky_opts.Update(env)
82211811Sbaz21@cam.ac.uk    nonsticky_opts.Update(env)
82311811Sbaz21@cam.ac.uk
82411811Sbaz21@cam.ac.uk    help_text += "\nSticky options for %s:\n" % build_dir \
82511235Sandreas.sandberg@arm.com                 + sticky_opts.GenerateHelpText(env) \
82611235Sandreas.sandberg@arm.com                 + "\nNon-sticky options for %s:\n" % build_dir \
82711235Sandreas.sandberg@arm.com                 + nonsticky_opts.GenerateHelpText(env)
82812563Sgabeblack@google.com
82912563Sgabeblack@google.com    # Process option settings.
83012563Sgabeblack@google.com
83111235Sandreas.sandberg@arm.com    if not have_fenv and env['USE_FENV']:
8327840Snate@binkert.org        print "Warning: <fenv.h> not available; " \
83312563Sgabeblack@google.com              "forcing USE_FENV to False in", build_dir + "."
8347840Snate@binkert.org        env['USE_FENV'] = False
8351858SN/A
8361858SN/A    if not env['USE_FENV']:
8371858SN/A        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
83812563Sgabeblack@google.com        print "         FP results may deviate slightly from other platforms."
83912563Sgabeblack@google.com
8401858SN/A    if env['EFENCE']:
84112230Sgiacomo.travaglini@arm.com        env.Append(LIBS=['efence'])
84212230Sgiacomo.travaglini@arm.com
84312230Sgiacomo.travaglini@arm.com    if env['USE_MYSQL']:
84412230Sgiacomo.travaglini@arm.com        if not have_mysql:
84512563Sgabeblack@google.com            print "Warning: MySQL not available; " \
84612563Sgabeblack@google.com                  "forcing USE_MYSQL to False in", build_dir + "."
84712563Sgabeblack@google.com            env['USE_MYSQL'] = False
84812230Sgiacomo.travaglini@arm.com        else:
8499903Sandreas.hansson@arm.com            print "Compiling in", build_dir, "with MySQL support."
8509903Sandreas.hansson@arm.com            env.ParseConfig(mysql_config_libs)
8519903Sandreas.hansson@arm.com            env.ParseConfig(mysql_config_include)
8529903Sandreas.hansson@arm.com
85310841Sandreas.sandberg@arm.com    # Save sticky option settings back to current options file
8549651SAndreas.Sandberg@ARM.com    sticky_opts.Save(current_opts_file, env)
85512563Sgabeblack@google.com
85612563Sgabeblack@google.com    if env['USE_SSE2']:
8579651SAndreas.Sandberg@ARM.com        env.Append(CCFLAGS='-msse2')
85812056Sgabeblack@google.com
85912056Sgabeblack@google.com    # The src/SConscript file sets up the build rules in 'env' according
86012056Sgabeblack@google.com    # to the configured options.  It returns a list of environments,
86112563Sgabeblack@google.com    # one for each variant build (debug, opt, etc.)
86212056Sgabeblack@google.com    envList = SConscript('src/SConscript', build_dir = build_path,
86310841Sandreas.sandberg@arm.com                         exports = 'env')
86410841Sandreas.sandberg@arm.com
86510841Sandreas.sandberg@arm.com    # Set up the regression tests for each build.
86610841Sandreas.sandberg@arm.com    for e in envList:
86710841Sandreas.sandberg@arm.com        SConscript('tests/SConscript',
86810841Sandreas.sandberg@arm.com                   build_dir = joinpath(build_path, 'tests', e.Label),
8699651SAndreas.Sandberg@ARM.com                   exports = { 'env' : e }, duplicate = False)
8709651SAndreas.Sandberg@ARM.com
8719651SAndreas.Sandberg@ARM.comHelp(help_text)
8729651SAndreas.Sandberg@ARM.com
8739651SAndreas.Sandberg@ARM.com
8749651SAndreas.Sandberg@ARM.com###################################################
87512563Sgabeblack@google.com#
8769651SAndreas.Sandberg@ARM.com# Let SCons do its thing.  At this point SCons will use the defined
8779651SAndreas.Sandberg@ARM.com# build environments to build the requested targets.
87810841Sandreas.sandberg@arm.com#
87912563Sgabeblack@google.com###################################################
88012563Sgabeblack@google.com
88110841Sandreas.sandberg@arm.com