SConstruct revision 6003
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.
294762Snate@binkert.org#
30955SN/A# Authors: Steve Reinhardt
315522Snate@binkert.org#          Nathan Binkert
326143Snate@binkert.org
334762Snate@binkert.org###################################################
345522Snate@binkert.org#
35955SN/A# SCons top-level build description (SConstruct) file.
365522Snate@binkert.org#
37955SN/A# While in this directory ('m5'), just type 'scons' to build the default
385522Snate@binkert.org# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
394202Sbinkertn@umich.edu# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
405742Snate@binkert.org# the optimized full-system version).
41955SN/A#
424381Sbinkertn@umich.edu# You can build M5 in a different directory as long as there is a
434381Sbinkertn@umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
448334Snate@binkert.org# expects that all configs under the same build directory are being
45955SN/A# built for the same host system.
46955SN/A#
474202Sbinkertn@umich.edu# Examples:
48955SN/A#
494382Sbinkertn@umich.edu#   The following two commands are equivalent.  The '-u' option tells
504382Sbinkertn@umich.edu#   scons to search up the directory tree for this SConstruct file.
514382Sbinkertn@umich.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
526654Snate@binkert.org#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
535517Snate@binkert.org#
548614Sgblack@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
557674Snate@binkert.org#   in a directory outside of the source tree.  The '-C' option tells
566143Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
576143Snate@binkert.org#   file.
586143Snate@binkert.org#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
598233Snate@binkert.org#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
608233Snate@binkert.org#
618233Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
628233Snate@binkert.org# 'm5' directory (or use -u or -C to tell scons where to find this
638233Snate@binkert.org# file), you can use 'scons -h' to print all the M5-specific build
648334Snate@binkert.org# options as well.
658334Snate@binkert.org#
6610453SAndrew.Bardsley@arm.com###################################################
6710453SAndrew.Bardsley@arm.com
688233Snate@binkert.org# Check for recent-enough Python and SCons versions.
698233Snate@binkert.orgtry:
708233Snate@binkert.org    # Really old versions of scons only take two options for the
718233Snate@binkert.org    # function, so check once without the revision and once with the
728233Snate@binkert.org    # revision, the first instance will fail for stuff other than
738233Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
746143Snate@binkert.org    EnsureSConsVersion(0, 98)
758233Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
768233Snate@binkert.orgexcept SystemExit, e:
778233Snate@binkert.org    print """
786143Snate@binkert.orgFor more details, see:
796143Snate@binkert.org    http://m5sim.org/wiki/index.php/Compiling_M5
806143Snate@binkert.org"""
816143Snate@binkert.org    raise
828233Snate@binkert.org
838233Snate@binkert.org# We ensure the python version early because we have stuff that
848233Snate@binkert.org# requires python 2.4
856143Snate@binkert.orgtry:
868233Snate@binkert.org    EnsurePythonVersion(2, 4)
878233Snate@binkert.orgexcept SystemExit, e:
888233Snate@binkert.org    print """
898233Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
906143Snate@binkert.orgeither (1) rearranging your PATH so that scons finds the non-default
916143Snate@binkert.org'python' first or (2) explicitly invoking an alternative interpreter
926143Snate@binkert.orgon the scons script.
934762Snate@binkert.org
946143Snate@binkert.orgFor more details, see:
958233Snate@binkert.org    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
968233Snate@binkert.org"""
978233Snate@binkert.org    raise
988233Snate@binkert.org
998233Snate@binkert.orgimport os
1006143Snate@binkert.orgimport re
1018233Snate@binkert.orgimport subprocess
1028233Snate@binkert.orgimport sys
1038233Snate@binkert.org
1048233Snate@binkert.orgfrom os import mkdir, environ
1056143Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1066143Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1076143Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1086143Snate@binkert.org
1096143Snate@binkert.orgimport SCons
1106143Snate@binkert.orgimport SCons.Node
1116143Snate@binkert.org
1126143Snate@binkert.orgdef read_command(cmd, **kwargs):
1136143Snate@binkert.org    """run the command cmd, read the results and return them
1147065Snate@binkert.org    this is sorta like `cmd` in shell"""
1156143Snate@binkert.org    from subprocess import Popen, PIPE, STDOUT
1168233Snate@binkert.org
1178233Snate@binkert.org    if isinstance(cmd, str):
1188233Snate@binkert.org        cmd = cmd.split()
1198233Snate@binkert.org
1208233Snate@binkert.org    no_exception = 'exception' in kwargs
1218233Snate@binkert.org    exception = kwargs.pop('exception', None)
1228233Snate@binkert.org    
1238233Snate@binkert.org    kwargs.setdefault('shell', False)
1248233Snate@binkert.org    kwargs.setdefault('stdout', PIPE)
1258233Snate@binkert.org    kwargs.setdefault('stderr', STDOUT)
1268233Snate@binkert.org    kwargs.setdefault('close_fds', True)
1278233Snate@binkert.org    try:
1288233Snate@binkert.org        subp = Popen(cmd, **kwargs)
1298233Snate@binkert.org    except Exception, e:
1308233Snate@binkert.org        if no_exception:
1318233Snate@binkert.org            return exception
1328233Snate@binkert.org        raise
1338233Snate@binkert.org
1348233Snate@binkert.org    return subp.communicate()[0]
1358233Snate@binkert.org
1368233Snate@binkert.org# helper function: compare arrays or strings of version numbers.
1378233Snate@binkert.org# E.g., compare_version((1,3,25), (1,4,1)')
1388233Snate@binkert.org# returns -1, 0, 1 if v1 is <, ==, > v2
1398233Snate@binkert.orgdef compare_versions(v1, v2):
1408233Snate@binkert.org    def make_version_list(v):
1418233Snate@binkert.org        if isinstance(v, (list,tuple)):
1428233Snate@binkert.org            return v
1438233Snate@binkert.org        elif isinstance(v, str):
1448233Snate@binkert.org            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
1458233Snate@binkert.org        else:
1468233Snate@binkert.org            raise TypeError
1476143Snate@binkert.org
1486143Snate@binkert.org    v1 = make_version_list(v1)
1496143Snate@binkert.org    v2 = make_version_list(v2)
1506143Snate@binkert.org    # Compare corresponding elements of lists
1516143Snate@binkert.org    for n1,n2 in zip(v1, v2):
1526143Snate@binkert.org        if n1 < n2: return -1
1539982Satgutier@umich.edu        if n1 > n2: return  1
15410196SCurtis.Dunham@arm.com    # all corresponding values are equal... see if one has extra values
15510196SCurtis.Dunham@arm.com    if len(v1) < len(v2): return -1
15610196SCurtis.Dunham@arm.com    if len(v1) > len(v2): return  1
15710196SCurtis.Dunham@arm.com    return 0
15810196SCurtis.Dunham@arm.com
15910196SCurtis.Dunham@arm.com########################################################################
16010196SCurtis.Dunham@arm.com#
16110196SCurtis.Dunham@arm.com# Set up the base build environment.
1626143Snate@binkert.org#
1636143Snate@binkert.org########################################################################
1648945Ssteve.reinhardt@amd.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
1658233Snate@binkert.org                 'RANLIB' ])
1668233Snate@binkert.org
1676143Snate@binkert.orguse_env = {}
1688945Ssteve.reinhardt@amd.comfor key,val in os.environ.iteritems():
1696143Snate@binkert.org    if key in use_vars or key.startswith("M5"):
1706143Snate@binkert.org        use_env[key] = val
1716143Snate@binkert.org
1726143Snate@binkert.orgenv = Environment(ENV=use_env)
1735522Snate@binkert.orgenv.root = Dir(".")          # The current directory (where this file lives).
1746143Snate@binkert.orgenv.srcdir = Dir("src")      # The source directory
1756143Snate@binkert.org
1766143Snate@binkert.org########################################################################
1779982Satgutier@umich.edu#
1788233Snate@binkert.org# Mercurial Stuff.
1798233Snate@binkert.org#
1808233Snate@binkert.org# If the M5 directory is a mercurial repository, we should do some
1816143Snate@binkert.org# extra things.
1826143Snate@binkert.org#
1836143Snate@binkert.org########################################################################
1846143Snate@binkert.org
1855522Snate@binkert.orghgdir = env.root.Dir(".hg")
1865522Snate@binkert.org
1875522Snate@binkert.orgmercurial_style_message = """
1885522Snate@binkert.orgYou're missing the M5 style hook.
1895604Snate@binkert.orgPlease install the hook so we can ensure that all code fits a common style.
1905604Snate@binkert.org
1916143Snate@binkert.orgAll you'd need to do is add the following lines to your repository .hg/hgrc
1926143Snate@binkert.orgor your personal .hgrc
1934762Snate@binkert.org----------------
1944762Snate@binkert.org
1956143Snate@binkert.org[extensions]
1966727Ssteve.reinhardt@amd.comstyle = %s/util/style.py
1976727Ssteve.reinhardt@amd.com
1986727Ssteve.reinhardt@amd.com[hooks]
1994762Snate@binkert.orgpretxncommit.style = python:style.check_whitespace
2006143Snate@binkert.org""" % (env.root)
2016143Snate@binkert.org
2026143Snate@binkert.orgmercurial_bin_not_found = """
2036143Snate@binkert.orgMercurial binary cannot be found, unfortunately this means that we
2046727Ssteve.reinhardt@amd.comcannot easily determine the version of M5 that you are running and
2056143Snate@binkert.orgthis makes error messages more difficult to collect.  Please consider
2067674Snate@binkert.orginstalling mercurial if you choose to post an error message
2077674Snate@binkert.org"""
2085604Snate@binkert.org
2096143Snate@binkert.orgmercurial_lib_not_found = """
2106143Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook
2116143Snate@binkert.orgIf you are actually a M5 developer, please fix this and
2124762Snate@binkert.orgrun the style hook. It is important.
2136143Snate@binkert.org"""
2144762Snate@binkert.org
2154762Snate@binkert.orghg_info = "Unknown"
2164762Snate@binkert.orgif hgdir.exists():
2176143Snate@binkert.org    # 1) Grab repository revision if we know it.
2186143Snate@binkert.org    cmd = "hg id -n -i -t -b"
2194762Snate@binkert.org    try:
2208233Snate@binkert.org        hg_info = read_command(cmd, cwd=env.root.abspath).strip()
2218233Snate@binkert.org    except OSError:
2228233Snate@binkert.org        print mercurial_bin_not_found
2238233Snate@binkert.org
2246143Snate@binkert.org    # 2) Ensure that the style hook is in place.
2256143Snate@binkert.org    try:
2264762Snate@binkert.org        ui = None
2276143Snate@binkert.org        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
2284762Snate@binkert.org            from mercurial import ui
2296143Snate@binkert.org            ui = ui.ui()
2304762Snate@binkert.org    except ImportError:
2316143Snate@binkert.org        print mercurial_lib_not_found
2328233Snate@binkert.org
2338233Snate@binkert.org    if ui is not None:
23410453SAndrew.Bardsley@arm.com        ui.readconfig(hgdir.File('hgrc').abspath)
2356143Snate@binkert.org        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2366143Snate@binkert.org
2376143Snate@binkert.org        if not style_hook:
2386143Snate@binkert.org            print mercurial_style_message
2396143Snate@binkert.org            sys.exit(1)
2406143Snate@binkert.orgelse:
2416143Snate@binkert.org    print ".hg directory not found"
2426143Snate@binkert.orgenv['HG_INFO'] = hg_info
24310453SAndrew.Bardsley@arm.com
24410453SAndrew.Bardsley@arm.com###################################################
245955SN/A#
2469396Sandreas.hansson@arm.com# Figure out which configurations to set up based on the path(s) of
2479396Sandreas.hansson@arm.com# the target(s).
2489396Sandreas.hansson@arm.com#
2499396Sandreas.hansson@arm.com###################################################
2509396Sandreas.hansson@arm.com
2519396Sandreas.hansson@arm.com# Find default configuration & binary.
2529396Sandreas.hansson@arm.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
2539396Sandreas.hansson@arm.com
2549396Sandreas.hansson@arm.com# helper function: find last occurrence of element in list
2559396Sandreas.hansson@arm.comdef rfind(l, elt, offs = -1):
2569396Sandreas.hansson@arm.com    for i in range(len(l)+offs, 0, -1):
2579396Sandreas.hansson@arm.com        if l[i] == elt:
2589396Sandreas.hansson@arm.com            return i
2599930Sandreas.hansson@arm.com    raise ValueError, "element not found"
2609930Sandreas.hansson@arm.com
2619396Sandreas.hansson@arm.com# Each target must have 'build' in the interior of the path; the
2628235Snate@binkert.org# directory below this will determine the build parameters.  For
2638235Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2646143Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
2658235Snate@binkert.org# follow 'build' in the bulid path.
2669003SAli.Saidi@ARM.com
2678235Snate@binkert.org# Generate absolute paths to targets so we can see where the build dir is
2688235Snate@binkert.orgif COMMAND_LINE_TARGETS:
2698235Snate@binkert.org    # Ask SCons which directory it was invoked from
2708235Snate@binkert.org    launch_dir = GetLaunchDir()
2718235Snate@binkert.org    # Make targets relative to invocation directory
2728235Snate@binkert.org    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2738235Snate@binkert.org                    COMMAND_LINE_TARGETS]
2748235Snate@binkert.orgelse:
2758235Snate@binkert.org    # Default targets are relative to root of tree
2768235Snate@binkert.org    abs_targets = [ normpath(joinpath(ROOT, str(x))) for x in \
2778235Snate@binkert.org                    DEFAULT_TARGETS]
2788235Snate@binkert.org
2798235Snate@binkert.org
2808235Snate@binkert.org# Generate a list of the unique build roots and configs that the
2819003SAli.Saidi@ARM.com# collected targets reference.
2828235Snate@binkert.orgvariant_paths = []
2835584Snate@binkert.orgbuild_root = None
2844382Sbinkertn@umich.edufor t in abs_targets:
2854202Sbinkertn@umich.edu    path_dirs = t.split('/')
2864382Sbinkertn@umich.edu    try:
2874382Sbinkertn@umich.edu        build_top = rfind(path_dirs, 'build', -2)
2884382Sbinkertn@umich.edu    except:
2899396Sandreas.hansson@arm.com        print "Error: no non-leaf 'build' dir found on target path", t
2905584Snate@binkert.org        Exit(1)
2914382Sbinkertn@umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2924382Sbinkertn@umich.edu    if not build_root:
2934382Sbinkertn@umich.edu        build_root = this_build_root
2948232Snate@binkert.org    else:
2955192Ssaidi@eecs.umich.edu        if this_build_root != build_root:
2968232Snate@binkert.org            print "Error: build targets not under same build root\n"\
2978232Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
2988232Snate@binkert.org            Exit(1)
2995192Ssaidi@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3008232Snate@binkert.org    if variant_path not in variant_paths:
3015192Ssaidi@eecs.umich.edu        variant_paths.append(variant_path)
3025799Snate@binkert.org
3038232Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
3045192Ssaidi@eecs.umich.eduif not isdir(build_root):
3055192Ssaidi@eecs.umich.edu    mkdir(build_root)
3065192Ssaidi@eecs.umich.edu
3078232Snate@binkert.orgExport('env')
3085192Ssaidi@eecs.umich.edu
3098232Snate@binkert.orgenv.SConsignFile(joinpath(build_root, "sconsign"))
3105192Ssaidi@eecs.umich.edu
3115192Ssaidi@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
3125192Ssaidi@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3135192Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3144382Sbinkertn@umich.edu# (soft) links work better.
3154382Sbinkertn@umich.eduenv.SetOption('duplicate', 'soft-copy')
3164382Sbinkertn@umich.edu
3172667Sstever@eecs.umich.edu#
3182667Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
3192667Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
3202667Sstever@eecs.umich.edu#
3212667Sstever@eecs.umich.edu
3222667Sstever@eecs.umich.edu# Variable validators & converters for global sticky variables
3235742Snate@binkert.orgdef PathListMakeAbsolute(val):
3245742Snate@binkert.org    if not val:
3255742Snate@binkert.org        return val
3265793Snate@binkert.org    f = lambda p: abspath(expanduser(p))
3278334Snate@binkert.org    return ':'.join(map(f, val.split(':')))
3285793Snate@binkert.org
3295793Snate@binkert.orgdef PathListAllExist(key, val, env):
3305793Snate@binkert.org    if not val:
3314382Sbinkertn@umich.edu        return
3324762Snate@binkert.org    paths = val.split(':')
3335344Sstever@gmail.com    for path in paths:
3344382Sbinkertn@umich.edu        if not isdir(path):
3355341Sstever@gmail.com            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3365742Snate@binkert.org
3375742Snate@binkert.orgglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3385742Snate@binkert.org
3395742Snate@binkert.orgglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3405742Snate@binkert.org
3414762Snate@binkert.orgglobal_sticky_vars.AddVariables(
3425742Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', env['CC'])),
3435742Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', env['CXX'])),
3447722Sgblack@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
3455742Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3465742Snate@binkert.org    ('EXTRAS', 'Add Extra directories to the compilation', '',
3475742Snate@binkert.org     PathListAllExist, PathListMakeAbsolute)
3489930Sandreas.hansson@arm.com    )    
3499930Sandreas.hansson@arm.com
3509930Sandreas.hansson@arm.com# base help text
3519930Sandreas.hansson@arm.comhelp_text = '''
3529930Sandreas.hansson@arm.comUsage: scons [scons options] [build options] [target(s)]
3535742Snate@binkert.org
3548242Sbradley.danofsky@amd.comGlobal sticky options:
3558242Sbradley.danofsky@amd.com'''
3568242Sbradley.danofsky@amd.com
3578242Sbradley.danofsky@amd.comhelp_text += global_sticky_vars.GenerateHelpText(env)
3585341Sstever@gmail.com
3595742Snate@binkert.org# Update env with values from ARGUMENTS & file global_sticky_vars_file
3607722Sgblack@eecs.umich.eduglobal_sticky_vars.Update(env)
3614773Snate@binkert.org
3626108Snate@binkert.org# Save sticky variable settings back to current variables file
3631858SN/Aglobal_sticky_vars.Save(global_sticky_vars_file, env)
3641085SN/A
3656658Snate@binkert.org# Parse EXTRAS variable to build list of all directories where we're
3666658Snate@binkert.org# look for sources etc.  This list is exported as base_dir_list.
3677673Snate@binkert.orgbase_dir = env.srcdir.abspath
3686658Snate@binkert.orgif env['EXTRAS']:
3696658Snate@binkert.org    extras_dir_list = env['EXTRAS'].split(':')
3706658Snate@binkert.orgelse:
3716658Snate@binkert.org    extras_dir_list = []
3726658Snate@binkert.org
3736658Snate@binkert.orgExport('base_dir')
3746658Snate@binkert.orgExport('extras_dir_list')
3757673Snate@binkert.org
3767673Snate@binkert.org# M5_PLY is used by isa_parser.py to find the PLY package.
3777673Snate@binkert.orgenv.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
3787673Snate@binkert.org
3797673Snate@binkert.orgCXX_version = read_command([env['CXX'],'--version'], exception=False)
3807673Snate@binkert.orgCXX_V = read_command([env['CXX'],'-V'], exception=False)
3817673Snate@binkert.org
3826658Snate@binkert.orgenv['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3837673Snate@binkert.orgenv['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
3847673Snate@binkert.orgenv['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
3857673Snate@binkert.orgif env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
3867673Snate@binkert.org    print 'Error: How can we have two at the same time?'
3877673Snate@binkert.org    Exit(1)
3887673Snate@binkert.org
3899048SAli.Saidi@ARM.com# Set up default C++ compiler flags
3907673Snate@binkert.orgif env['GCC']:
3917673Snate@binkert.org    env.Append(CCFLAGS='-pipe')
3927673Snate@binkert.org    env.Append(CCFLAGS='-fno-strict-aliasing')
3937673Snate@binkert.org    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
3946658Snate@binkert.org    env.Append(CXXFLAGS='-Wno-deprecated')
3957756SAli.Saidi@ARM.comelif env['ICC']:
3967816Ssteve.reinhardt@amd.com    pass #Fix me... add warning flags once we clean up icc warnings
3976658Snate@binkert.orgelif env['SUNCC']:
3984382Sbinkertn@umich.edu    env.Append(CCFLAGS='-Qoption ccfe')
3994382Sbinkertn@umich.edu    env.Append(CCFLAGS='-features=gcc')
4004762Snate@binkert.org    env.Append(CCFLAGS='-features=extensions')
4014762Snate@binkert.org    env.Append(CCFLAGS='-library=stlport4')
4024762Snate@binkert.org    env.Append(CCFLAGS='-xar')
4036654Snate@binkert.org    #env.Append(CCFLAGS='-instances=semiexplicit')
4046654Snate@binkert.orgelse:
4055517Snate@binkert.org    print 'Error: Don\'t know what compiler options to use for your compiler.'
4065517Snate@binkert.org    print '       Please fix SConstruct and src/SConscript and try again.'
4075517Snate@binkert.org    Exit(1)
4085517Snate@binkert.org
4095517Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
4105517Snate@binkert.org# extra 'qdo' every time we run scons.
4115517Snate@binkert.orgif env['BATCH']:
4125517Snate@binkert.org    env['CC']     = env['BATCH_CMD'] + ' ' + env['CC']
4135517Snate@binkert.org    env['CXX']    = env['BATCH_CMD'] + ' ' + env['CXX']
4145517Snate@binkert.org    env['AS']     = env['BATCH_CMD'] + ' ' + env['AS']
4155517Snate@binkert.org    env['AR']     = env['BATCH_CMD'] + ' ' + env['AR']
4165517Snate@binkert.org    env['RANLIB'] = env['BATCH_CMD'] + ' ' + env['RANLIB']
4175517Snate@binkert.org
4185517Snate@binkert.orgif sys.platform == 'cygwin':
4195517Snate@binkert.org    # cygwin has some header file issues...
4205517Snate@binkert.org    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
4215517Snate@binkert.orgenv.Append(CPPPATH=[Dir('ext/dnet')])
4226654Snate@binkert.org
4235517Snate@binkert.org# Check for SWIG
4245517Snate@binkert.orgif not env.has_key('SWIG'):
4255517Snate@binkert.org    print 'Error: SWIG utility not found.'
4265517Snate@binkert.org    print '       Please install (see http://www.swig.org) and retry.'
4275517Snate@binkert.org    Exit(1)
4285517Snate@binkert.org
4295517Snate@binkert.org# Check for appropriate SWIG version
4305517Snate@binkert.orgswig_version = read_command(('swig', '-version'), exception='').split()
4316143Snate@binkert.org# First 3 words should be "SWIG Version x.y.z"
4326654Snate@binkert.orgif len(swig_version) < 3 or \
4335517Snate@binkert.org        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
4345517Snate@binkert.org    print 'Error determining SWIG version.'
4355517Snate@binkert.org    Exit(1)
4365517Snate@binkert.org
4375517Snate@binkert.orgmin_swig_version = '1.3.28'
4385517Snate@binkert.orgif compare_versions(swig_version[2], min_swig_version) < 0:
4395517Snate@binkert.org    print 'Error: SWIG version', min_swig_version, 'or newer required.'
4405517Snate@binkert.org    print '       Installed version:', swig_version[2]
4415517Snate@binkert.org    Exit(1)
4425517Snate@binkert.org
4435517Snate@binkert.org# Set up SWIG flags & scanner
4445517Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
4455517Snate@binkert.orgenv.Append(SWIGFLAGS=swig_flags)
4465517Snate@binkert.org
4476654Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
4486654Snate@binkert.org# stuff for some reason
4495517Snate@binkert.orgscanners = []
4505517Snate@binkert.orgfor scanner in env['SCANNERS']:
4516143Snate@binkert.org    skeys = scanner.skeys
4526143Snate@binkert.org    if skeys == '.i':
4536143Snate@binkert.org        continue
4546727Ssteve.reinhardt@amd.com
4555517Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
4566727Ssteve.reinhardt@amd.com        continue
4575517Snate@binkert.org
4585517Snate@binkert.org    scanners.append(scanner)
4595517Snate@binkert.org
4606654Snate@binkert.org# add the new swig scanner that we like better
4616654Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
4627673Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
4636654Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
4646654Snate@binkert.org
4656654Snate@binkert.org# replace the scanners list that has what we want
4666654Snate@binkert.orgenv['SCANNERS'] = scanners
4675517Snate@binkert.org
4685517Snate@binkert.org# Add a custom Check function to the Configure context so that we can
4695517Snate@binkert.org# figure out if the compiler adds leading underscores to global
4706143Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
4715517Snate@binkert.org# use for embedding the python code.
4724762Snate@binkert.orgdef CheckLeading(context):
4735517Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
4745517Snate@binkert.org    # 1) Define a global variable called x from asm so the C compiler
4756143Snate@binkert.org    #    won't change the symbol at all.
4766143Snate@binkert.org    # 2) Declare that variable.
4775517Snate@binkert.org    # 3) Use the variable
4785517Snate@binkert.org    #
4795517Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
4805517Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
4815517Snate@binkert.org    # was defined by the asm statement.  If the compiler does not
4825517Snate@binkert.org    # prepend an underscore, this will not successfully link because
4835517Snate@binkert.org    # '_x' will have been defined by assembly, while the C portion of
4845517Snate@binkert.org    # the code will be trying to use 'x'
4855517Snate@binkert.org    ret = context.TryLink('''
4869338SAndreas.Sandberg@arm.com        asm(".globl _x; _x: .byte 0");
4879338SAndreas.Sandberg@arm.com        extern int x;
4889338SAndreas.Sandberg@arm.com        int main() { return x; }
4899338SAndreas.Sandberg@arm.com        ''', extension=".c")
4909338SAndreas.Sandberg@arm.com    context.env.Append(LEADING_UNDERSCORE=ret)
4919338SAndreas.Sandberg@arm.com    context.Result(ret)
4928596Ssteve.reinhardt@amd.com    return ret
4938596Ssteve.reinhardt@amd.com
4948596Ssteve.reinhardt@amd.com# Platform-specific configuration.  Note again that we assume that all
4958596Ssteve.reinhardt@amd.com# builds under a given build root run on the same host platform.
4968596Ssteve.reinhardt@amd.comconf = Configure(env,
4978596Ssteve.reinhardt@amd.com                 conf_dir = joinpath(build_root, '.scons_config'),
4988596Ssteve.reinhardt@amd.com                 log_file = joinpath(build_root, 'scons_config.log'),
4996143Snate@binkert.org                 custom_tests = { 'CheckLeading' : CheckLeading })
5005517Snate@binkert.org
5016654Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
5026654Snate@binkert.org# way so don't need to check the return code.
5036654Snate@binkert.orgconf.CheckLeading()
5046654Snate@binkert.org
5056654Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
5066654Snate@binkert.orgtry:
5075517Snate@binkert.org    import platform
5085517Snate@binkert.org    uname = platform.uname()
5095517Snate@binkert.org    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
5108596Ssteve.reinhardt@amd.com        if int(read_command('sysctl -n hw.cpu64bit_capable')[0]):
5118596Ssteve.reinhardt@amd.com            env.Append(CCFLAGS='-arch x86_64')
5124762Snate@binkert.org            env.Append(CFLAGS='-arch x86_64')
5134762Snate@binkert.org            env.Append(LINKFLAGS='-arch x86_64')
5144762Snate@binkert.org            env.Append(ASFLAGS='-arch x86_64')
5154762Snate@binkert.orgexcept:
5164762Snate@binkert.org    pass
5174762Snate@binkert.org
5187675Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
5194762Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
5204762Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
5214762Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
5224762Snate@binkert.org# more optimistic null object that returns True instead.
5234382Sbinkertn@umich.eduif not conf:
5244382Sbinkertn@umich.edu    def NullCheck(*args, **kwargs):
5255517Snate@binkert.org        return True
5266654Snate@binkert.org
5275517Snate@binkert.org    class NullConf:
5288126Sgblack@eecs.umich.edu        def __init__(self, env):
5296654Snate@binkert.org            self.env = env
5307673Snate@binkert.org        def Finish(self):
5316654Snate@binkert.org            return self.env
5326654Snate@binkert.org        def __getattr__(self, mname):
5336654Snate@binkert.org            return NullCheck
5346654Snate@binkert.org
5356654Snate@binkert.org    conf = NullConf(env)
5366654Snate@binkert.org
5376654Snate@binkert.org# Find Python include and library directories for embedding the
5386669Snate@binkert.org# interpreter.  For consistency, we will use the same Python
5396669Snate@binkert.org# installation used to run scons (and thus this script).  If you want
5406669Snate@binkert.org# to link in an alternate version, see above for instructions on how
5416669Snate@binkert.org# to invoke scons with a different copy of the Python interpreter.
5426669Snate@binkert.orgfrom distutils import sysconfig
5436669Snate@binkert.org
5446654Snate@binkert.orgpy_getvar = sysconfig.get_config_var
5457673Snate@binkert.org
5465517Snate@binkert.orgpy_version = 'python' + py_getvar('VERSION')
5478126Sgblack@eecs.umich.edu
5485798Snate@binkert.orgpy_general_include = sysconfig.get_python_inc()
5497756SAli.Saidi@ARM.compy_platform_include = sysconfig.get_python_inc(plat_specific=True)
5507816Ssteve.reinhardt@amd.compy_includes = [ py_general_include ]
5515798Snate@binkert.orgif py_platform_include != py_general_include:
5525798Snate@binkert.org    py_includes.append(py_platform_include)
5535517Snate@binkert.org
5545517Snate@binkert.orgpy_lib_path = [ py_getvar('LIBDIR') ]
5557673Snate@binkert.org# add the prefix/lib/pythonX.Y/config dir, but only if there is no
5565517Snate@binkert.org# shared library in prefix/lib/.
5575517Snate@binkert.orgif not py_getvar('Py_ENABLE_SHARED'):
5587673Snate@binkert.org    py_lib_path.append('-L' + py_getvar('LIBPL'))
5597673Snate@binkert.org
5605517Snate@binkert.orgpy_libs = []
5615798Snate@binkert.orgfor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
5625798Snate@binkert.org    if lib not in py_libs:
5638333Snate@binkert.org        py_libs.append(lib)
5647816Ssteve.reinhardt@amd.compy_libs.append('-l' + py_version)
5655798Snate@binkert.org
5665798Snate@binkert.orgenv.Append(CPPPATH=py_includes)
5674762Snate@binkert.orgenv.Append(LIBPATH=py_lib_path)
5684762Snate@binkert.org
5694762Snate@binkert.org# verify that this stuff works
5704762Snate@binkert.orgif not conf.CheckHeader('Python.h', '<>'):
5714762Snate@binkert.org    print "Error: can't find Python.h header in", py_includes
5728596Ssteve.reinhardt@amd.com    Exit(1)
5735517Snate@binkert.org
5745517Snate@binkert.orgfor lib in py_libs:
5755517Snate@binkert.org    assert lib.startswith('-l')
5765517Snate@binkert.org    lib = lib[2:]
5775517Snate@binkert.org    if not conf.CheckLib(lib):
5787673Snate@binkert.org        print "Error: can't find library %s required by python" % lib
5798596Ssteve.reinhardt@amd.com        Exit(1)
5807673Snate@binkert.org
5815517Snate@binkert.org# On Solaris you need to use libsocket for socket ops
5828596Ssteve.reinhardt@amd.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5835517Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5845517Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
5855517Snate@binkert.org       Exit(1)
5868596Ssteve.reinhardt@amd.com
5875517Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
5887673Snate@binkert.org# added to the LIBS environment variable.
5897673Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
5907673Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
5915517Snate@binkert.org          'and/or zlib.h header file.'
5925517Snate@binkert.org    print '       Please install zlib and try again.'
5935517Snate@binkert.org    Exit(1)
5945517Snate@binkert.org
5955517Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
5965517Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
5975517Snate@binkert.orgif not have_fenv:
5987673Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
5997673Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
6007673Snate@binkert.org
6015517Snate@binkert.org######################################################################
6028596Ssteve.reinhardt@amd.com#
6035517Snate@binkert.org# Check for mysql.
6045517Snate@binkert.org#
6055517Snate@binkert.orgmysql_config = WhereIs('mysql_config')
6065517Snate@binkert.orghave_mysql = bool(mysql_config)
6075517Snate@binkert.org
6087673Snate@binkert.org# Check MySQL version.
6097673Snate@binkert.orgif have_mysql:
6107673Snate@binkert.org    mysql_version = read_command(mysql_config + ' --version')
6115517Snate@binkert.org    min_mysql_version = '4.1'
6128596Ssteve.reinhardt@amd.com    if compare_versions(mysql_version, min_mysql_version) < 0:
6137675Snate@binkert.org        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
6147675Snate@binkert.org        print '         Version', mysql_version, 'detected.'
6157675Snate@binkert.org        have_mysql = False
6167675Snate@binkert.org
6177675Snate@binkert.org# Set up mysql_config commands.
6187675Snate@binkert.orgif have_mysql:
6198596Ssteve.reinhardt@amd.com    mysql_config_include = mysql_config + ' --include'
6207675Snate@binkert.org    if os.system(mysql_config_include + ' > /dev/null') != 0:
6217675Snate@binkert.org        # older mysql_config versions don't support --include, use
6228596Ssteve.reinhardt@amd.com        # --cflags instead
6238596Ssteve.reinhardt@amd.com        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
6248596Ssteve.reinhardt@amd.com    # This seems to work in all versions
6258596Ssteve.reinhardt@amd.com    mysql_config_libs = mysql_config + ' --libs'
6268596Ssteve.reinhardt@amd.com
6278596Ssteve.reinhardt@amd.com######################################################################
6288596Ssteve.reinhardt@amd.com#
6298596Ssteve.reinhardt@amd.com# Finish the configuration
63010454SCurtis.Dunham@arm.com#
63110454SCurtis.Dunham@arm.comenv = conf.Finish()
63210454SCurtis.Dunham@arm.com
63310454SCurtis.Dunham@arm.com######################################################################
6348596Ssteve.reinhardt@amd.com#
6354762Snate@binkert.org# Collect all non-global variables
6366143Snate@binkert.org#
6376143Snate@binkert.org
6386143Snate@binkert.orgExport('env')
6394762Snate@binkert.org
6404762Snate@binkert.org# Define the universe of supported ISAs
6414762Snate@binkert.orgall_isa_list = [ ]
6427756SAli.Saidi@ARM.comExport('all_isa_list')
6438596Ssteve.reinhardt@amd.com
6444762Snate@binkert.org# Define the universe of supported CPU models
64510454SCurtis.Dunham@arm.comall_cpu_list = [ ]
6464762Snate@binkert.orgdefault_cpus = [ ]
6478596Ssteve.reinhardt@amd.comExport('all_cpu_list', 'default_cpus')
6485463Snate@binkert.org
6498596Ssteve.reinhardt@amd.com# Sticky variables get saved in the variables file so they persist from
6508596Ssteve.reinhardt@amd.com# one invocation to the next (unless overridden, in which case the new
6515463Snate@binkert.org# value becomes sticky).
6527756SAli.Saidi@ARM.comsticky_vars = Variables(args=ARGUMENTS)
6538596Ssteve.reinhardt@amd.comExport('sticky_vars')
6544762Snate@binkert.org
65510454SCurtis.Dunham@arm.com# Non-sticky variables only apply to the current build.
6567677Snate@binkert.orgnonsticky_vars = Variables(args=ARGUMENTS)
6574762Snate@binkert.orgExport('nonsticky_vars')
6584762Snate@binkert.org
6596143Snate@binkert.org# Walk the tree and execute all SConsopts scripts that wil add to the
6606143Snate@binkert.org# above variables
6616143Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
6624762Snate@binkert.org    for root, dirs, files in os.walk(bdir):
6634762Snate@binkert.org        if 'SConsopts' in files:
6647756SAli.Saidi@ARM.com            print "Reading", joinpath(root, 'SConsopts')
6657816Ssteve.reinhardt@amd.com            SConscript(joinpath(root, 'SConsopts'))
6664762Snate@binkert.org
66710454SCurtis.Dunham@arm.comall_isa_list.sort()
6684762Snate@binkert.orgall_cpu_list.sort()
6694762Snate@binkert.orgdefault_cpus.sort()
6704762Snate@binkert.org
6717756SAli.Saidi@ARM.comsticky_vars.AddVariables(
6728596Ssteve.reinhardt@amd.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
6734762Snate@binkert.org    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
67410454SCurtis.Dunham@arm.com    ListVariable('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
6754762Snate@binkert.org    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
6767677Snate@binkert.org    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
6777756SAli.Saidi@ARM.com                 False),
6788596Ssteve.reinhardt@amd.com    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
6797675Snate@binkert.org                 False),
68010454SCurtis.Dunham@arm.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
6817677Snate@binkert.org                 False),
6825517Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
6838596Ssteve.reinhardt@amd.com                 'Make floating-point results compatible with SimpleScalar',
6849248SAndreas.Sandberg@arm.com                 False),
6859248SAndreas.Sandberg@arm.com    BoolVariable('USE_SSE2',
6869248SAndreas.Sandberg@arm.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
6879248SAndreas.Sandberg@arm.com                 False),
6888596Ssteve.reinhardt@amd.com    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
6898596Ssteve.reinhardt@amd.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
6908596Ssteve.reinhardt@amd.com    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
6919248SAndreas.Sandberg@arm.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
6928596Ssteve.reinhardt@amd.com    )
6934762Snate@binkert.org
6947674Snate@binkert.orgnonsticky_vars.AddVariables(
6957674Snate@binkert.org    BoolVariable('update_ref', 'Update test reference outputs', False)
6967674Snate@binkert.org    )
6977674Snate@binkert.org
6987674Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
6997674Snate@binkert.orgenv.ExportVariables = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
7007674Snate@binkert.org                       'USE_MYSQL', 'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', \
7017674Snate@binkert.org                       'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', \
7027674Snate@binkert.org                       'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
7037674Snate@binkert.org
7047674Snate@binkert.org###################################################
7057674Snate@binkert.org#
7067674Snate@binkert.org# Define a SCons builder for configuration flag headers.
7077674Snate@binkert.org#
7087674Snate@binkert.org###################################################
7094762Snate@binkert.org
7106143Snate@binkert.org# This function generates a config header file that #defines the
7116143Snate@binkert.org# variable symbol to the current variable setting (0 or 1).  The source
7127756SAli.Saidi@ARM.com# operands are the name of the variable and a Value node containing the
7137816Ssteve.reinhardt@amd.com# value of the variable.
7148235Snate@binkert.orgdef build_config_file(target, source, env):
7158596Ssteve.reinhardt@amd.com    (variable, value) = [s.get_contents() for s in source]
7167756SAli.Saidi@ARM.com    f = file(str(target[0]), 'w')
7177816Ssteve.reinhardt@amd.com    print >> f, '#define', variable, value
71810454SCurtis.Dunham@arm.com    f.close()
7198235Snate@binkert.org    return None
7204382Sbinkertn@umich.edu
7219396Sandreas.hansson@arm.com# Generate the message to be printed when building the config file.
7229396Sandreas.hansson@arm.comdef build_config_file_string(target, source, env):
7239396Sandreas.hansson@arm.com    (variable, value) = [s.get_contents() for s in source]
7249396Sandreas.hansson@arm.com    return "Defining %s as %s in %s." % (variable, value, target[0])
7259396Sandreas.hansson@arm.com
7269396Sandreas.hansson@arm.com# Combine the two functions into a scons Action object.
7279396Sandreas.hansson@arm.comconfig_action = Action(build_config_file, build_config_file_string)
7289396Sandreas.hansson@arm.com
7299396Sandreas.hansson@arm.com# The emitter munges the source & target node lists to reflect what
7309396Sandreas.hansson@arm.com# we're really doing.
7319396Sandreas.hansson@arm.comdef config_emitter(target, source, env):
7329396Sandreas.hansson@arm.com    # extract variable name from Builder arg
73310454SCurtis.Dunham@arm.com    variable = str(target[0])
7349396Sandreas.hansson@arm.com    # True target is config header file
7359396Sandreas.hansson@arm.com    target = joinpath('config', variable.lower() + '.hh')
7369396Sandreas.hansson@arm.com    val = env[variable]
7379396Sandreas.hansson@arm.com    if isinstance(val, bool):
7389396Sandreas.hansson@arm.com        # Force value to 0/1
7399396Sandreas.hansson@arm.com        val = int(val)
7408232Snate@binkert.org    elif isinstance(val, str):
7418232Snate@binkert.org        val = '"' + val + '"'
7428232Snate@binkert.org
7438232Snate@binkert.org    # Sources are variable name & value (packaged in SCons Value nodes)
7448232Snate@binkert.org    return ([target], [Value(variable), Value(val)])
7456229Snate@binkert.org
74610455SCurtis.Dunham@arm.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
7476229Snate@binkert.org
74810455SCurtis.Dunham@arm.comenv.Append(BUILDERS = { 'ConfigFile' : config_builder })
74910455SCurtis.Dunham@arm.com
75010455SCurtis.Dunham@arm.com# libelf build is shared across all configs in the build root.
7515517Snate@binkert.orgenv.SConscript('ext/libelf/SConscript',
7525517Snate@binkert.org               variant_dir = joinpath(build_root, 'libelf'))
7537673Snate@binkert.org
7545517Snate@binkert.org# gzstream build is shared across all configs in the build root.
75510455SCurtis.Dunham@arm.comenv.SConscript('ext/gzstream/SConscript',
7565517Snate@binkert.org               variant_dir = joinpath(build_root, 'gzstream'))
7575517Snate@binkert.org
7588232Snate@binkert.org###################################################
75910455SCurtis.Dunham@arm.com#
76010455SCurtis.Dunham@arm.com# This function is used to set up a directory with switching headers
76110455SCurtis.Dunham@arm.com#
7627673Snate@binkert.org###################################################
7637673Snate@binkert.org
76410455SCurtis.Dunham@arm.comenv['ALL_ISA_LIST'] = all_isa_list
76510455SCurtis.Dunham@arm.comdef make_switching_dir(dname, switch_headers, env):
76610455SCurtis.Dunham@arm.com    # Generate the header.  target[0] is the full path of the output
7675517Snate@binkert.org    # header to generate.  'source' is a dummy variable, since we get the
76810455SCurtis.Dunham@arm.com    # list of ISAs from env['ALL_ISA_LIST'].
76910455SCurtis.Dunham@arm.com    def gen_switch_hdr(target, source, env):
77010455SCurtis.Dunham@arm.com        fname = str(target[0])
77110455SCurtis.Dunham@arm.com        bname = basename(fname)
77210455SCurtis.Dunham@arm.com        f = open(fname, 'w')
77310455SCurtis.Dunham@arm.com        f.write('#include "arch/isa_specific.hh"\n')
77410455SCurtis.Dunham@arm.com        cond = '#if'
77510455SCurtis.Dunham@arm.com        for isa in all_isa_list:
77610455SCurtis.Dunham@arm.com            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
77710455SCurtis.Dunham@arm.com                    % (cond, isa.upper(), dname, isa, bname))
77810455SCurtis.Dunham@arm.com            cond = '#elif'
77910455SCurtis.Dunham@arm.com        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
7805517Snate@binkert.org        f.close()
78110455SCurtis.Dunham@arm.com        return 0
7828232Snate@binkert.org
7838232Snate@binkert.org    # String to print when generating header
7845517Snate@binkert.org    def gen_switch_hdr_string(target, source, env):
7857673Snate@binkert.org        return "Generating switch header " + str(target[0])
7865517Snate@binkert.org
7878232Snate@binkert.org    # Build SCons Action object. 'varlist' specifies env vars that this
7888232Snate@binkert.org    # action depends on; when env['ALL_ISA_LIST'] changes these actions
7895517Snate@binkert.org    # should get re-executed.
7908232Snate@binkert.org    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
7918232Snate@binkert.org                               varlist=['ALL_ISA_LIST'])
7928232Snate@binkert.org
7937673Snate@binkert.org    # Instantiate actions for each header
7945517Snate@binkert.org    for hdr in switch_headers:
7955517Snate@binkert.org        env.Command(hdr, [], switch_hdr_action)
7967673Snate@binkert.orgExport('make_switching_dir')
7975517Snate@binkert.org
79810455SCurtis.Dunham@arm.com###################################################
7995517Snate@binkert.org#
8005517Snate@binkert.org# Define build environments for selected configurations.
8018232Snate@binkert.org#
8028232Snate@binkert.org###################################################
8035517Snate@binkert.org
8048232Snate@binkert.org# rename base env
8058232Snate@binkert.orgbase_env = env
8065517Snate@binkert.org
8078232Snate@binkert.orgfor variant_path in variant_paths:
8088232Snate@binkert.org    print "Building in", variant_path
8098232Snate@binkert.org
8105517Snate@binkert.org    # Make a copy of the build-root environment to use for this config.
8118232Snate@binkert.org    env = base_env.Clone()
8128232Snate@binkert.org    env['BUILDDIR'] = variant_path
8138232Snate@binkert.org
8148232Snate@binkert.org    # variant_dir is the tail component of build path, and is used to
8158232Snate@binkert.org    # determine the build parameters (e.g., 'ALPHA_SE')
8168232Snate@binkert.org    (build_root, variant_dir) = splitpath(variant_path)
8175517Snate@binkert.org
8188232Snate@binkert.org    # Set env variables according to the build directory config.
8198232Snate@binkert.org    sticky_vars.files = []
8205517Snate@binkert.org    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
8218232Snate@binkert.org    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
8227673Snate@binkert.org    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
8235517Snate@binkert.org    current_vars_file = joinpath(build_root, 'variables', variant_dir)
8247673Snate@binkert.org    if isfile(current_vars_file):
8255517Snate@binkert.org        sticky_vars.files.append(current_vars_file)
8268232Snate@binkert.org        print "Using saved variables file %s" % current_vars_file
8278232Snate@binkert.org    else:
8288232Snate@binkert.org        # Build dir-specific variables file doesn't exist.
8295192Ssaidi@eecs.umich.edu
83010454SCurtis.Dunham@arm.com        # Make sure the directory is there so we can create it later
83110454SCurtis.Dunham@arm.com        opt_dir = dirname(current_vars_file)
8328232Snate@binkert.org        if not isdir(opt_dir):
83310455SCurtis.Dunham@arm.com            mkdir(opt_dir)
83410455SCurtis.Dunham@arm.com
83510455SCurtis.Dunham@arm.com        # Get default build variables from source tree.  Variables are
83610455SCurtis.Dunham@arm.com        # normally determined by name of $VARIANT_DIR, but can be
83710455SCurtis.Dunham@arm.com        # overriden by 'default=' arg on command line.
83810455SCurtis.Dunham@arm.com        default_vars_file = joinpath('build_opts',
8395192Ssaidi@eecs.umich.edu                                     ARGUMENTS.get('default', variant_dir))
8407674Snate@binkert.org        if isfile(default_vars_file):
8415522Snate@binkert.org            sticky_vars.files.append(default_vars_file)
8425522Snate@binkert.org            print "Variables file %s not found,\n  using defaults in %s" \
8437674Snate@binkert.org                  % (current_vars_file, default_vars_file)
8447674Snate@binkert.org        else:
8457674Snate@binkert.org            print "Error: cannot find variables file %s or %s" \
8467674Snate@binkert.org                  % (current_vars_file, default_vars_file)
8477674Snate@binkert.org            Exit(1)
8487674Snate@binkert.org
8497674Snate@binkert.org    # Apply current variable settings to env
8507674Snate@binkert.org    sticky_vars.Update(env)
8515522Snate@binkert.org    nonsticky_vars.Update(env)
8525522Snate@binkert.org
8535522Snate@binkert.org    help_text += "\nSticky variables for %s:\n" % variant_dir \
8545517Snate@binkert.org                 + sticky_vars.GenerateHelpText(env) \
8555522Snate@binkert.org                 + "\nNon-sticky variables for %s:\n" % variant_dir \
8565517Snate@binkert.org                 + nonsticky_vars.GenerateHelpText(env)
8576143Snate@binkert.org
8586727Ssteve.reinhardt@amd.com    # Process variable settings.
8595522Snate@binkert.org
8605522Snate@binkert.org    if not have_fenv and env['USE_FENV']:
8615522Snate@binkert.org        print "Warning: <fenv.h> not available; " \
8627674Snate@binkert.org              "forcing USE_FENV to False in", variant_dir + "."
8635517Snate@binkert.org        env['USE_FENV'] = False
8647673Snate@binkert.org
8657673Snate@binkert.org    if not env['USE_FENV']:
8667674Snate@binkert.org        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
8677673Snate@binkert.org        print "         FP results may deviate slightly from other platforms."
8687674Snate@binkert.org
8697674Snate@binkert.org    if env['EFENCE']:
8708946Sandreas.hansson@arm.com        env.Append(LIBS=['efence'])
8717674Snate@binkert.org
8727674Snate@binkert.org    if env['USE_MYSQL']:
8737674Snate@binkert.org        if not have_mysql:
8745522Snate@binkert.org            print "Warning: MySQL not available; " \
8755522Snate@binkert.org                  "forcing USE_MYSQL to False in", variant_dir + "."
8767674Snate@binkert.org            env['USE_MYSQL'] = False
8777674Snate@binkert.org        else:
8787674Snate@binkert.org            print "Compiling in", variant_dir, "with MySQL support."
8797674Snate@binkert.org            env.ParseConfig(mysql_config_libs)
8807673Snate@binkert.org            env.ParseConfig(mysql_config_include)
8817674Snate@binkert.org
8827674Snate@binkert.org    # Save sticky variable settings back to current variables file
8837674Snate@binkert.org    sticky_vars.Save(current_vars_file, env)
8847674Snate@binkert.org
8857674Snate@binkert.org    if env['USE_SSE2']:
8867674Snate@binkert.org        env.Append(CCFLAGS='-msse2')
8877674Snate@binkert.org
8887674Snate@binkert.org    # The src/SConscript file sets up the build rules in 'env' according
8897811Ssteve.reinhardt@amd.com    # to the configured variables.  It returns a list of environments,
8907674Snate@binkert.org    # one for each variant build (debug, opt, etc.)
8917673Snate@binkert.org    envList = SConscript('src/SConscript', variant_dir = variant_path,
8925522Snate@binkert.org                         exports = 'env')
8936143Snate@binkert.org
89410453SAndrew.Bardsley@arm.com    # Set up the regression tests for each build.
8957816Ssteve.reinhardt@amd.com    for e in envList:
89610454SCurtis.Dunham@arm.com        SConscript('tests/SConscript',
89710453SAndrew.Bardsley@arm.com                   variant_dir = joinpath(variant_path, 'tests', e.Label),
8984382Sbinkertn@umich.edu                   exports = { 'env' : e }, duplicate = False)
8994382Sbinkertn@umich.edu
9004382Sbinkertn@umich.eduHelp(help_text)
9014382Sbinkertn@umich.edu