SConstruct revision 9986
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013 ARM Limited
45871Snate@binkert.org# All rights reserved.
51762SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
312665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
325863Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
388878Ssteve.reinhardt@amd.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
392632Sstever@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
408878Ssteve.reinhardt@amd.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42955SN/A#
438878Ssteve.reinhardt@amd.com# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452761Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
538878Ssteve.reinhardt@amd.com# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562761Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582761Sstever@eecs.umich.edu# built for the same host system.
598878Ssteve.reinhardt@amd.com#
608878Ssteve.reinhardt@amd.com# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
638878Ssteve.reinhardt@amd.com#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
652632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
68955SN/A#   in a directory outside of the source tree.  The '-C' option tells
695863Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705863Snate@binkert.org#   file.
715863Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725863Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735863Snate@binkert.org#
745863Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
755863Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
765863Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
775863Snate@binkert.org# options as well.
785863Snate@binkert.org#
795863Snate@binkert.org###################################################
808878Ssteve.reinhardt@amd.com
815863Snate@binkert.org# Check for recent-enough Python and SCons versions.
825863Snate@binkert.orgtry:
835863Snate@binkert.org    # Really old versions of scons only take two options for the
845863Snate@binkert.org    # function, so check once without the revision and once with the
855863Snate@binkert.org    # revision, the first instance will fail for stuff other than
865863Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
875863Snate@binkert.org    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
905863Snate@binkert.org    print """
915863Snate@binkert.orgFor more details, see:
925863Snate@binkert.org    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
955863Snate@binkert.org
968878Ssteve.reinhardt@amd.com# We ensure the python version early because because python-config
975863Snate@binkert.org# requires python 2.5
985863Snate@binkert.orgtry:
995863Snate@binkert.org    EnsurePythonVersion(2, 5)
1006654Snate@binkert.orgexcept SystemExit, e:
101955SN/A    print """
1025396Ssaidi@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1035863Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1045863Snate@binkert.org'python-config' first.
1054202Sbinkertn@umich.edu
1065863Snate@binkert.orgFor more details, see:
1075863Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1085863Snate@binkert.org"""
1095863Snate@binkert.org    raise
110955SN/A
1116654Snate@binkert.org# Global Python includes
1125273Sstever@gmail.comimport os
1135871Snate@binkert.orgimport re
1145273Sstever@gmail.comimport subprocess
1156655Snate@binkert.orgimport sys
1168878Ssteve.reinhardt@amd.com
1176655Snate@binkert.orgfrom os import mkdir, environ
1186655Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1199219Spower.jg@gmail.comfrom os.path import exists,  isdir, isfile
1206655Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1215871Snate@binkert.org
1226654Snate@binkert.org# SCons includes
1238947Sandreas.hansson@arm.comimport SCons
1245396Ssaidi@eecs.umich.eduimport SCons.Node
1258120Sgblack@eecs.umich.edu
1268120Sgblack@eecs.umich.eduextra_python_paths = [
1278120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1288120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1298120Sgblack@eecs.umich.edu    ]
1308120Sgblack@eecs.umich.edu
1318120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1328120Sgblack@eecs.umich.edu
1338879Ssteve.reinhardt@amd.comfrom m5.util import compareVersions, readCommand
1348879Ssteve.reinhardt@amd.comfrom m5.util.terminal import get_termcap
1358879Ssteve.reinhardt@amd.com
1368879Ssteve.reinhardt@amd.comhelp_texts = {
1378879Ssteve.reinhardt@amd.com    "options" : "",
1388879Ssteve.reinhardt@amd.com    "global_vars" : "",
1398879Ssteve.reinhardt@amd.com    "local_vars" : ""
1408879Ssteve.reinhardt@amd.com}
1418879Ssteve.reinhardt@amd.com
1428879Ssteve.reinhardt@amd.comExport("help_texts")
1438879Ssteve.reinhardt@amd.com
1448879Ssteve.reinhardt@amd.com
1458879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1468120Sgblack@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1478120Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1488120Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1498120Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1508120Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1518120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1528120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1538120Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1548120Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1558120Sgblack@eecs.umich.edu# we can just use AddOption directly.
1568120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1578120Sgblack@eecs.umich.edu    col_width = 30
1588120Sgblack@eecs.umich.edu
1598120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1608879Ssteve.reinhardt@amd.com    if "help" in kwargs:
1618879Ssteve.reinhardt@amd.com        length = len(help)
1628879Ssteve.reinhardt@amd.com        if length >= col_width:
1638879Ssteve.reinhardt@amd.com            help += "\n" + " " * col_width
1648879Ssteve.reinhardt@amd.com        else:
1658879Ssteve.reinhardt@amd.com            help += " " * (col_width - length)
1668879Ssteve.reinhardt@amd.com        help += kwargs["help"]
1678879Ssteve.reinhardt@amd.com    help_texts["options"] += help + "\n"
1689227Sandreas.hansson@arm.com
1699227Sandreas.hansson@arm.com    AddOption(*args, **kwargs)
1708879Ssteve.reinhardt@amd.com
1718879Ssteve.reinhardt@amd.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1728879Ssteve.reinhardt@amd.com               help="Add color to abbreviated scons output")
1738879Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1748120Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1758947Sandreas.hansson@arm.comAddLocalOption('--default', dest='default', type='string', action='store',
1767816Ssteve.reinhardt@amd.com               help='Override which build_opts file to use for defaults')
1775871Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1785871Snate@binkert.org               help='Disable style checking hooks')
1796121Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1805871Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1815871Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1829119Sandreas.hansson@arm.com               help='Update test reference outputs')
1839119Sandreas.hansson@arm.comAddLocalOption('--verbose', dest='verbose', action='store_true',
184955SN/A               help='Print full tool command lines')
1855871Snate@binkert.org
1865871Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1875871Snate@binkert.org
1885871Snate@binkert.org########################################################################
189955SN/A#
1906121Snate@binkert.org# Set up the main build environment.
1918881Smarc.orr@gmail.com#
1926121Snate@binkert.org########################################################################
1936121Snate@binkert.org
1941533SN/A# export TERM so that clang reports errors in color
1956655Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1966655Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1976655Snate@binkert.org                 'RANLIB', 'SWIG', 'TERM' ])
1986655Snate@binkert.org
1995871Snate@binkert.orguse_prefixes = [
2005871Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
2015863Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2025871Snate@binkert.org    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2038878Ssteve.reinhardt@amd.com    "CCC_",         # clang static analyzer configuration
2045871Snate@binkert.org    ]
2055871Snate@binkert.org
2065871Snate@binkert.orguse_env = {}
2075863Snate@binkert.orgfor key,val in os.environ.iteritems():
2086121Snate@binkert.org    if key in use_vars or \
2095863Snate@binkert.org            any([key.startswith(prefix) for prefix in use_prefixes]):
2105871Snate@binkert.org        use_env[key] = val
2118336Ssteve.reinhardt@amd.com
2128336Ssteve.reinhardt@amd.commain = Environment(ENV=use_env)
2138336Ssteve.reinhardt@amd.commain.Decider('MD5-timestamp')
2148336Ssteve.reinhardt@amd.commain.root = Dir(".")         # The current directory (where this file lives).
2154678Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
2168336Ssteve.reinhardt@amd.com
2178336Ssteve.reinhardt@amd.commain_dict_keys = main.Dictionary().keys()
2188336Ssteve.reinhardt@amd.com
2194678Snate@binkert.org# Check that we have a C/C++ compiler
2204678Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2214678Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2224678Snate@binkert.org    Exit(1)
2237827Snate@binkert.org
2247827Snate@binkert.org# Check that swig is present
2258336Ssteve.reinhardt@amd.comif not 'SWIG' in main_dict_keys:
2264678Snate@binkert.org    print "swig is not installed (package swig on Ubuntu and RedHat)"
2278336Ssteve.reinhardt@amd.com    Exit(1)
2288336Ssteve.reinhardt@amd.com
2298336Ssteve.reinhardt@amd.com# add useful python code PYTHONPATH so it can be used by subprocesses
2308336Ssteve.reinhardt@amd.com# as well
2318336Ssteve.reinhardt@amd.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2328336Ssteve.reinhardt@amd.com
2335871Snate@binkert.org########################################################################
2345871Snate@binkert.org#
2358336Ssteve.reinhardt@amd.com# Mercurial Stuff.
2368336Ssteve.reinhardt@amd.com#
2378336Ssteve.reinhardt@amd.com# If the gem5 directory is a mercurial repository, we should do some
2388336Ssteve.reinhardt@amd.com# extra things.
2398336Ssteve.reinhardt@amd.com#
2405871Snate@binkert.org########################################################################
2418336Ssteve.reinhardt@amd.com
2428336Ssteve.reinhardt@amd.comhgdir = main.root.Dir(".hg")
2438336Ssteve.reinhardt@amd.com
2448336Ssteve.reinhardt@amd.commercurial_style_message = """
2458336Ssteve.reinhardt@amd.comYou're missing the gem5 style hook, which automatically checks your code
2464678Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
2475871Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
2484678Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2498336Ssteve.reinhardt@amd.com
2508336Ssteve.reinhardt@amd.commercurial_style_hook = """
2518336Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2528336Ssteve.reinhardt@amd.com# to provide the gem5 style-checking hooks
2538336Ssteve.reinhardt@amd.com[extensions]
2548336Ssteve.reinhardt@amd.comstyle = %s/util/style.py
2558336Ssteve.reinhardt@amd.com
2568336Ssteve.reinhardt@amd.com[hooks]
2578336Ssteve.reinhardt@amd.compretxncommit.style = python:style.check_style
2588336Ssteve.reinhardt@amd.compre-qrefresh.style = python:style.check_style
2598336Ssteve.reinhardt@amd.com# End of SConstruct additions
2608336Ssteve.reinhardt@amd.com
2618336Ssteve.reinhardt@amd.com""" % (main.root.abspath)
2628336Ssteve.reinhardt@amd.com
2638336Ssteve.reinhardt@amd.commercurial_lib_not_found = """
2648336Ssteve.reinhardt@amd.comMercurial libraries cannot be found, ignoring style hook.  If
2658336Ssteve.reinhardt@amd.comyou are a gem5 developer, please fix this and run the style
2665871Snate@binkert.orghook. It is important.
2676121Snate@binkert.org"""
268955SN/A
269955SN/A# Check for style hook and prompt for installation if it's not there.
2702632Sstever@eecs.umich.edu# Skip this if --ignore-style was specified, there's no .hg dir to
2712632Sstever@eecs.umich.edu# install a hook in, or there's no interactive terminal to prompt.
272955SN/Aif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
273955SN/A    style_hook = True
274955SN/A    try:
275955SN/A        from mercurial import ui
2768878Ssteve.reinhardt@amd.com        ui = ui.ui()
277955SN/A        ui.readconfig(hgdir.File('hgrc').abspath)
2782632Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2792632Sstever@eecs.umich.edu                     ui.config('hooks', 'pre-qrefresh.style', None)
2802632Sstever@eecs.umich.edu    except ImportError:
2812632Sstever@eecs.umich.edu        print mercurial_lib_not_found
2822632Sstever@eecs.umich.edu
2832632Sstever@eecs.umich.edu    if not style_hook:
2842632Sstever@eecs.umich.edu        print mercurial_style_message,
2858268Ssteve.reinhardt@amd.com        # continue unless user does ctrl-c/ctrl-d etc.
2868268Ssteve.reinhardt@amd.com        try:
2878268Ssteve.reinhardt@amd.com            raw_input()
2888268Ssteve.reinhardt@amd.com        except:
2898268Ssteve.reinhardt@amd.com            print "Input exception, exiting scons.\n"
2908268Ssteve.reinhardt@amd.com            sys.exit(1)
2918268Ssteve.reinhardt@amd.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2922632Sstever@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
2932632Sstever@eecs.umich.edu        try:
2942632Sstever@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
2952632Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
2968268Ssteve.reinhardt@amd.com            hgrc.close()
2972632Sstever@eecs.umich.edu        except:
2988268Ssteve.reinhardt@amd.com            print "Error updating", hgrc_path
2998268Ssteve.reinhardt@amd.com            sys.exit(1)
3008268Ssteve.reinhardt@amd.com
3018268Ssteve.reinhardt@amd.com
3023718Sstever@eecs.umich.edu###################################################
3032634Sstever@eecs.umich.edu#
3042634Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
3055863Snate@binkert.org# the target(s).
3062638Sstever@eecs.umich.edu#
3078268Ssteve.reinhardt@amd.com###################################################
3082632Sstever@eecs.umich.edu
3092632Sstever@eecs.umich.edu# Find default configuration & binary.
3102632Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3112632Sstever@eecs.umich.edu
3122632Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
3131858SN/Adef rfind(l, elt, offs = -1):
3143716Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
3152638Sstever@eecs.umich.edu        if l[i] == elt:
3162638Sstever@eecs.umich.edu            return i
3172638Sstever@eecs.umich.edu    raise ValueError, "element not found"
3182638Sstever@eecs.umich.edu
3192638Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3202638Sstever@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
3212638Sstever@eecs.umich.edu# relative to the launch directory unless a different root is provided
3225863Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3235863Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
3245863Snate@binkert.org            for p in path_list]
325955SN/A
3265341Sstever@gmail.com# Each target must have 'build' in the interior of the path; the
3275341Sstever@gmail.com# directory below this will determine the build parameters.  For
3285863Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3297756SAli.Saidi@ARM.com# recognize that ALPHA_SE specifies the configuration because it
3305341Sstever@gmail.com# follow 'build' in the build path.
3316121Snate@binkert.org
3324494Ssaidi@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
3336121Snate@binkert.org# in place rather than reassign the symbol to a new list, which
3341105SN/A# doesn't work (obviously!).
3352667Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3362667Sstever@eecs.umich.edu
3372667Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
3382667Sstever@eecs.umich.edu# collected targets reference.
3396121Snate@binkert.orgvariant_paths = []
3402667Sstever@eecs.umich.edubuild_root = None
3415341Sstever@gmail.comfor t in BUILD_TARGETS:
3425863Snate@binkert.org    path_dirs = t.split('/')
3435341Sstever@gmail.com    try:
3445341Sstever@gmail.com        build_top = rfind(path_dirs, 'build', -2)
3455341Sstever@gmail.com    except:
3468120Sgblack@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3475341Sstever@gmail.com        Exit(1)
3488120Sgblack@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3495341Sstever@gmail.com    if not build_root:
3508120Sgblack@eecs.umich.edu        build_root = this_build_root
3516121Snate@binkert.org    else:
3526121Snate@binkert.org        if this_build_root != build_root:
3538980Ssteve.reinhardt@amd.com            print "Error: build targets not under same build root\n"\
3545397Ssaidi@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
3555397Ssaidi@eecs.umich.edu            Exit(1)
3567727SAli.Saidi@ARM.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
3578268Ssteve.reinhardt@amd.com    if variant_path not in variant_paths:
3586168Snate@binkert.org        variant_paths.append(variant_path)
3595341Sstever@gmail.com
3608120Sgblack@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
3618120Sgblack@eecs.umich.eduif not isdir(build_root):
3628120Sgblack@eecs.umich.edu    mkdir(build_root)
3636814Sgblack@eecs.umich.edumain['BUILDROOT'] = build_root
3645863Snate@binkert.org
3658120Sgblack@eecs.umich.eduExport('main')
3665341Sstever@gmail.com
3675863Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3688268Ssteve.reinhardt@amd.com
3696121Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3706121Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
3718268Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
3725742Snate@binkert.org# (soft) links work better.
3735742Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
3745341Sstever@gmail.com
3755742Snate@binkert.org#
3765742Snate@binkert.org# Set up global sticky variables... these are common to an entire build
3775341Sstever@gmail.com# tree (not specific to a particular build like ALPHA_SE)
3786017Snate@binkert.org#
3796121Snate@binkert.org
3806017Snate@binkert.orgglobal_vars_file = joinpath(build_root, 'variables.global')
3817816Ssteve.reinhardt@amd.com
3827756SAli.Saidi@ARM.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3837756SAli.Saidi@ARM.com
3847756SAli.Saidi@ARM.comglobal_vars.AddVariables(
3857756SAli.Saidi@ARM.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3867756SAli.Saidi@ARM.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3877756SAli.Saidi@ARM.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3887756SAli.Saidi@ARM.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3897756SAli.Saidi@ARM.com    ('BATCH', 'Use batch pool for build and tests', False),
3907816Ssteve.reinhardt@amd.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3917816Ssteve.reinhardt@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3927816Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
3937816Ssteve.reinhardt@amd.com    )
3947816Ssteve.reinhardt@amd.com
3957816Ssteve.reinhardt@amd.com# Update main environment with values from ARGUMENTS & global_vars_file
3967816Ssteve.reinhardt@amd.comglobal_vars.Update(main)
3977816Ssteve.reinhardt@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3987816Ssteve.reinhardt@amd.com
3997816Ssteve.reinhardt@amd.com# Save sticky variable settings back to current variables file
4007756SAli.Saidi@ARM.comglobal_vars.Save(global_vars_file, main)
4017816Ssteve.reinhardt@amd.com
4027816Ssteve.reinhardt@amd.com# Parse EXTRAS variable to build list of all directories where we're
4037816Ssteve.reinhardt@amd.com# look for sources etc.  This list is exported as extras_dir_list.
4047816Ssteve.reinhardt@amd.combase_dir = main.srcdir.abspath
4057816Ssteve.reinhardt@amd.comif main['EXTRAS']:
4067816Ssteve.reinhardt@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4077816Ssteve.reinhardt@amd.comelse:
4087816Ssteve.reinhardt@amd.com    extras_dir_list = []
4097816Ssteve.reinhardt@amd.com
4107816Ssteve.reinhardt@amd.comExport('base_dir')
4117816Ssteve.reinhardt@amd.comExport('extras_dir_list')
4127816Ssteve.reinhardt@amd.com
4137816Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
4147816Ssteve.reinhardt@amd.commain.Append(CPPPATH=[Dir('ext')])
4157816Ssteve.reinhardt@amd.com
4167816Ssteve.reinhardt@amd.comdef strip_build_path(path, env):
4177816Ssteve.reinhardt@amd.com    path = str(path)
4187816Ssteve.reinhardt@amd.com    variant_base = env['BUILDROOT'] + os.path.sep
4197816Ssteve.reinhardt@amd.com    if path.startswith(variant_base):
4207816Ssteve.reinhardt@amd.com        path = path[len(variant_base):]
4217816Ssteve.reinhardt@amd.com    elif path.startswith('build/'):
4227816Ssteve.reinhardt@amd.com        path = path[6:]
4237816Ssteve.reinhardt@amd.com    return path
4247816Ssteve.reinhardt@amd.com
4257816Ssteve.reinhardt@amd.com# Generate a string of the form:
4267816Ssteve.reinhardt@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
4277816Ssteve.reinhardt@amd.com# to print while building.
4287816Ssteve.reinhardt@amd.comclass Transform(object):
4297816Ssteve.reinhardt@amd.com    # all specific color settings should be here and nowhere else
4307816Ssteve.reinhardt@amd.com    tool_color = termcap.Normal
4317816Ssteve.reinhardt@amd.com    pfx_color = termcap.Yellow
4327816Ssteve.reinhardt@amd.com    srcs_color = termcap.Yellow + termcap.Bold
4337816Ssteve.reinhardt@amd.com    arrow_color = termcap.Blue + termcap.Bold
4347816Ssteve.reinhardt@amd.com    tgts_color = termcap.Yellow + termcap.Bold
4357816Ssteve.reinhardt@amd.com
4367816Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
4377816Ssteve.reinhardt@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
4387816Ssteve.reinhardt@amd.com                      + self.pfx_color + "%s" \
4397816Ssteve.reinhardt@amd.com                      + self.srcs_color + "%s" \
4407816Ssteve.reinhardt@amd.com                      + self.arrow_color + " -> " \
4417816Ssteve.reinhardt@amd.com                      + self.tgts_color + "%s" \
4427816Ssteve.reinhardt@amd.com                      + termcap.Normal
4437816Ssteve.reinhardt@amd.com        self.max_sources = max_sources
4447816Ssteve.reinhardt@amd.com
4457816Ssteve.reinhardt@amd.com    def __call__(self, target, source, env, for_signature=None):
4467816Ssteve.reinhardt@amd.com        # truncate source list according to max_sources param
4477816Ssteve.reinhardt@amd.com        source = source[0:self.max_sources]
4487816Ssteve.reinhardt@amd.com        def strip(f):
4497816Ssteve.reinhardt@amd.com            return strip_build_path(str(f), env)
4507816Ssteve.reinhardt@amd.com        if len(source) > 0:
4517816Ssteve.reinhardt@amd.com            srcs = map(strip, source)
4527816Ssteve.reinhardt@amd.com        else:
4537816Ssteve.reinhardt@amd.com            srcs = ['']
4547816Ssteve.reinhardt@amd.com        tgts = map(strip, target)
4557816Ssteve.reinhardt@amd.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4567816Ssteve.reinhardt@amd.com        # operation that has nothing to do with paths.
4577816Ssteve.reinhardt@amd.com        com_pfx = os.path.commonprefix(srcs + tgts)
4587816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4597816Ssteve.reinhardt@amd.com        if com_pfx:
4607816Ssteve.reinhardt@amd.com            # do some cleanup and sanity checking on common prefix
4617816Ssteve.reinhardt@amd.com            if com_pfx[-1] == ".":
4628947Sandreas.hansson@arm.com                # prefix matches all but file extension: ok
4638947Sandreas.hansson@arm.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4647756SAli.Saidi@ARM.com                com_pfx = com_pfx[0:-1]
4658120Sgblack@eecs.umich.edu            elif com_pfx[-1] == "/":
4667756SAli.Saidi@ARM.com                # common prefix is directory path: OK
4677756SAli.Saidi@ARM.com                pass
4687756SAli.Saidi@ARM.com            else:
4697756SAli.Saidi@ARM.com                src0_len = len(srcs[0])
4707816Ssteve.reinhardt@amd.com                tgt0_len = len(tgts[0])
4717816Ssteve.reinhardt@amd.com                if src0_len == com_pfx_len:
4727816Ssteve.reinhardt@amd.com                    # source is a substring of target, OK
4737816Ssteve.reinhardt@amd.com                    pass
4747816Ssteve.reinhardt@amd.com                elif tgt0_len == com_pfx_len:
4757816Ssteve.reinhardt@amd.com                    # target is a substring of source, need to back up to
4767816Ssteve.reinhardt@amd.com                    # avoid empty string on RHS of arrow
4777816Ssteve.reinhardt@amd.com                    sep_idx = com_pfx.rfind(".")
4787816Ssteve.reinhardt@amd.com                    if sep_idx != -1:
4797816Ssteve.reinhardt@amd.com                        com_pfx = com_pfx[0:sep_idx]
4807756SAli.Saidi@ARM.com                    else:
4817756SAli.Saidi@ARM.com                        com_pfx = ''
4829227Sandreas.hansson@arm.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4839227Sandreas.hansson@arm.com                    # still splitting at file extension: ok
4849227Sandreas.hansson@arm.com                    pass
4859227Sandreas.hansson@arm.com                else:
4866654Snate@binkert.org                    # probably a fluke; ignore it
4876654Snate@binkert.org                    com_pfx = ''
4885871Snate@binkert.org        # recalculate length in case com_pfx was modified
4896121Snate@binkert.org        com_pfx_len = len(com_pfx)
4906121Snate@binkert.org        def fmt(files):
4916121Snate@binkert.org            f = map(lambda s: s[com_pfx_len:], files)
4928946Sandreas.hansson@arm.com            return ', '.join(f)
4938737Skoansin.tan@gmail.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4943940Ssaidi@eecs.umich.edu
4953918Ssaidi@eecs.umich.eduExport('Transform')
4963918Ssaidi@eecs.umich.edu
4971858SN/A# enable the regression script to use the termcap
4986121Snate@binkert.orgmain['TERMCAP'] = termcap
4997739Sgblack@eecs.umich.edu
5007739Sgblack@eecs.umich.eduif GetOption('verbose'):
5016143Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
5027618SAli.Saidi@arm.com        return Action(action, *args, **kwargs)
5037618SAli.Saidi@arm.comelse:
5047618SAli.Saidi@arm.com    MakeAction = Action
5057618SAli.Saidi@arm.com    main['CCCOMSTR']        = Transform("CC")
5068614Sgblack@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
5077618SAli.Saidi@arm.com    main['ASCOMSTR']        = Transform("AS")
5087618SAli.Saidi@arm.com    main['SWIGCOMSTR']      = Transform("SWIG")
5097618SAli.Saidi@arm.com    main['ARCOMSTR']        = Transform("AR", 0)
5107739Sgblack@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
5119224Sandreas.hansson@arm.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5129224Sandreas.hansson@arm.com    main['M4COMSTR']        = Transform("M4")
5139224Sandreas.hansson@arm.com    main['SHCCCOMSTR']      = Transform("SHCC")
5148946Sandreas.hansson@arm.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
5159227Sandreas.hansson@arm.comExport('MakeAction')
5169227Sandreas.hansson@arm.com
5179227Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
5189227Sandreas.hansson@arm.commain['LTO_CCFLAGS'] = []
5199227Sandreas.hansson@arm.commain['LTO_LDFLAGS'] = []
5209227Sandreas.hansson@arm.com
5219227Sandreas.hansson@arm.com# According to the readme, tcmalloc works best if the compiler doesn't
5229227Sandreas.hansson@arm.com# assume that we're using the builtin malloc and friends. These flags
5239227Sandreas.hansson@arm.com# are compiler-specific, so we need to set them after we detect which
5249227Sandreas.hansson@arm.com# compiler we're using.
5259227Sandreas.hansson@arm.commain['TCMALLOC_CCFLAGS'] = []
5269227Sandreas.hansson@arm.com
5279227Sandreas.hansson@arm.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5289227Sandreas.hansson@arm.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5299227Sandreas.hansson@arm.com
5309227Sandreas.hansson@arm.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5319227Sandreas.hansson@arm.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5329227Sandreas.hansson@arm.comif main['GCC'] + main['CLANG'] > 1:
5336121Snate@binkert.org    print 'Error: How can we have two at the same time?'
5343940Ssaidi@eecs.umich.edu    Exit(1)
5356121Snate@binkert.org
5367739Sgblack@eecs.umich.edu# Set up default C++ compiler flags
5377739Sgblack@eecs.umich.eduif main['GCC'] or main['CLANG']:
5387739Sgblack@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
5397739Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
5407739Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5417739Sgblack@eecs.umich.edu    # Enable -Wall and then disable the few warnings that we
5428737Skoansin.tan@gmail.com    # consistently violate
5438737Skoansin.tan@gmail.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5448737Skoansin.tan@gmail.com    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5458737Skoansin.tan@gmail.com    # actually use that name, so we stick with c++0x
5468737Skoansin.tan@gmail.com    main.Append(CXXFLAGS=['-std=c++0x'])
5478737Skoansin.tan@gmail.com    # Add selected sanity checks from -Wextra
5488737Skoansin.tan@gmail.com    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5498737Skoansin.tan@gmail.com                          '-Woverloaded-virtual'])
5508737Skoansin.tan@gmail.comelse:
5518737Skoansin.tan@gmail.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5528737Skoansin.tan@gmail.com    print "Don't know what compiler options to use for your compiler."
5538737Skoansin.tan@gmail.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5548737Skoansin.tan@gmail.com    print termcap.Yellow + '       version:' + termcap.Normal,
5558737Skoansin.tan@gmail.com    if not CXX_version:
5568737Skoansin.tan@gmail.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5578737Skoansin.tan@gmail.com               termcap.Normal
5588737Skoansin.tan@gmail.com    else:
5598737Skoansin.tan@gmail.com        print CXX_version.replace('\n', '<nl>')
5608946Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
5618946Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
5628946Sandreas.hansson@arm.com    print "       environment."
5638946Sandreas.hansson@arm.com    print "       "
5649224Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
5659224Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
5668946Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
5678946Sandreas.hansson@arm.com    Exit(1)
5683918Ssaidi@eecs.umich.edu
5699068SAli.Saidi@ARM.comif main['GCC']:
5709068SAli.Saidi@ARM.com    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5719068SAli.Saidi@ARM.com    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5729068SAli.Saidi@ARM.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5739068SAli.Saidi@ARM.com    if compareVersions(gcc_version, "4.4") < 0:
5749068SAli.Saidi@ARM.com        print 'Error: gcc version 4.4 or newer required.'
5759068SAli.Saidi@ARM.com        print '       Installed version:', gcc_version
5769068SAli.Saidi@ARM.com        Exit(1)
5779068SAli.Saidi@ARM.com
5789068SAli.Saidi@ARM.com    main['GCC_VERSION'] = gcc_version
5799068SAli.Saidi@ARM.com
5809068SAli.Saidi@ARM.com    # Check for versions with bugs
5819068SAli.Saidi@ARM.com    if not compareVersions(gcc_version, '4.4.1') or \
5829068SAli.Saidi@ARM.com       not compareVersions(gcc_version, '4.4.2'):
5839068SAli.Saidi@ARM.com        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5849068SAli.Saidi@ARM.com        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5853918Ssaidi@eecs.umich.edu
5863918Ssaidi@eecs.umich.edu    # LTO support is only really working properly from 4.6 and beyond
5876157Snate@binkert.org    if compareVersions(gcc_version, '4.6') >= 0:
5886157Snate@binkert.org        # Add the appropriate Link-Time Optimization (LTO) flags
5896157Snate@binkert.org        # unless LTO is explicitly turned off. Note that these flags
5906157Snate@binkert.org        # are only used by the fast target.
5915397Ssaidi@eecs.umich.edu        if not GetOption('no_lto'):
5925397Ssaidi@eecs.umich.edu            # Pass the LTO flag when compiling to produce GIMPLE
5936121Snate@binkert.org            # output, we merely create the flags here and only append
5946121Snate@binkert.org            # them later/
5956121Snate@binkert.org            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5966121Snate@binkert.org
5976121Snate@binkert.org            # Use the same amount of jobs for LTO as we are running
5986121Snate@binkert.org            # scons with, we hardcode the use of the linker plugin
5995397Ssaidi@eecs.umich.edu            # which requires either gold or GNU ld >= 2.21
6001851SN/A            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
6011851SN/A                                   '-fuse-linker-plugin']
6027739Sgblack@eecs.umich.edu
603955SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6043053Sstever@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6056121Snate@binkert.org
6063053Sstever@eecs.umich.eduelif main['CLANG']:
6073053Sstever@eecs.umich.edu    # Check for a supported version of clang, >= 2.9 is needed to
6083053Sstever@eecs.umich.edu    # support similar features as gcc 4.4. See
6093053Sstever@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
6103053Sstever@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
6119072Sandreas.hansson@arm.com    clang_version_match = clang_version_re.match(CXX_version)
6123053Sstever@eecs.umich.edu    if (clang_version_match):
6134742Sstever@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
6144742Sstever@eecs.umich.edu        if compareVersions(clang_version, "2.9") < 0:
6153053Sstever@eecs.umich.edu            print 'Error: clang version 2.9 or newer required.'
6163053Sstever@eecs.umich.edu            print '       Installed version:', clang_version
6173053Sstever@eecs.umich.edu            Exit(1)
6188960Ssteve.reinhardt@amd.com    else:
6196654Snate@binkert.org        print 'Error: Unable to determine clang version.'
6203053Sstever@eecs.umich.edu        Exit(1)
6213053Sstever@eecs.umich.edu
6223053Sstever@eecs.umich.edu    # clang has a few additional warnings that we disable,
6233053Sstever@eecs.umich.edu    # tautological comparisons are allowed due to unsigned integers
6242667Sstever@eecs.umich.edu    # being compared to constants that happen to be 0, and extraneous
6254554Sbinkertn@umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
6266121Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
6272667Sstever@eecs.umich.edu    # is relying on this
6284554Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Wno-tautological-compare',
6294554Sbinkertn@umich.edu                         '-Wno-parentheses',
6304554Sbinkertn@umich.edu                         '-Wno-self-assign'])
6316121Snate@binkert.org
6324554Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6334554Sbinkertn@umich.edu
6344554Sbinkertn@umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6354781Snate@binkert.org    # opposed to libstdc++, as the later is dated.
6364554Sbinkertn@umich.edu    if sys.platform == "darwin":
6374554Sbinkertn@umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
6382667Sstever@eecs.umich.edu        main.Append(LIBS=['c++'])
6394554Sbinkertn@umich.edu
6404554Sbinkertn@umich.eduelse:
6414554Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6424554Sbinkertn@umich.edu    print "Don't know what compiler options to use for your compiler."
6432667Sstever@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6444554Sbinkertn@umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6452667Sstever@eecs.umich.edu    if not CXX_version:
6464554Sbinkertn@umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6476121Snate@binkert.org               termcap.Normal
6482667Sstever@eecs.umich.edu    else:
6495522Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
6505522Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
6515522Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
6525522Snate@binkert.org    print "       environment."
6535522Snate@binkert.org    print "       "
6545522Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6555522Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
6565522Snate@binkert.org    print "       src/SConscript to support that compiler."
6575522Snate@binkert.org    Exit(1)
6585522Snate@binkert.org
6595522Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
6605522Snate@binkert.orgmain['YACCFLAGS'] = '-d'
6615522Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
6625522Snate@binkert.org
6635522Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
6645522Snate@binkert.org# extra 'qdo' every time we run scons.
6655522Snate@binkert.orgif main['BATCH']:
6665522Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6675522Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6685522Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6695522Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6705522Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6715522Snate@binkert.org
6725522Snate@binkert.orgif sys.platform == 'cygwin':
6735522Snate@binkert.org    # cygwin has some header file issues...
6745522Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
6752638Sstever@eecs.umich.edu
6762638Sstever@eecs.umich.edu# Check for the protobuf compiler
6776121Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
6783716Sstever@eecs.umich.edu                             exception='').split()
6795522Snate@binkert.org
6805522Snate@binkert.org# First two words should be "libprotoc x.y.z"
6815522Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6825522Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
6835522Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6845522Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
6851858SN/A        termcap.Normal
6865227Ssaidi@eecs.umich.edu    main['PROTOC'] = False
6875227Ssaidi@eecs.umich.eduelse:
6885227Ssaidi@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
6895227Ssaidi@eecs.umich.edu    # require 2.1.0
6906654Snate@binkert.org    min_protoc_version = '2.1.0'
6916654Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6927769SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + \
6937769SAli.Saidi@ARM.com            'Warning: protoc version', min_protoc_version, \
6947769SAli.Saidi@ARM.com            'or newer required.\n' + \
6957769SAli.Saidi@ARM.com            '         Installed version:', protoc_version[1], \
6965227Ssaidi@eecs.umich.edu            termcap.Normal
6975227Ssaidi@eecs.umich.edu        main['PROTOC'] = False
6985227Ssaidi@eecs.umich.edu    else:
6995204Sstever@gmail.com        # Attempt to determine the appropriate include path and
7005204Sstever@gmail.com        # library path using pkg-config, that means we also need to
7015204Sstever@gmail.com        # check for pkg-config. Note that it is possible to use
7025204Sstever@gmail.com        # protobuf without the involvement of pkg-config. Later on we
7035204Sstever@gmail.com        # check go a library config check and at that point the test
7045204Sstever@gmail.com        # will fail if libprotobuf cannot be found.
7055204Sstever@gmail.com        if readCommand(['pkg-config', '--version'], exception=''):
7065204Sstever@gmail.com            try:
7075204Sstever@gmail.com                # Attempt to establish what linking flags to add for protobuf
7085204Sstever@gmail.com                # using pkg-config
7095204Sstever@gmail.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7105204Sstever@gmail.com            except:
7115204Sstever@gmail.com                print termcap.Yellow + termcap.Bold + \
7125204Sstever@gmail.com                    'Warning: pkg-config could not get protobuf flags.' + \
7135204Sstever@gmail.com                    termcap.Normal
7145204Sstever@gmail.com
7155204Sstever@gmail.com# Check for SWIG
7166121Snate@binkert.orgif not main.has_key('SWIG'):
7175204Sstever@gmail.com    print 'Error: SWIG utility not found.'
7183118Sstever@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
7193118Sstever@eecs.umich.edu    Exit(1)
7203118Sstever@eecs.umich.edu
7213118Sstever@eecs.umich.edu# Check for appropriate SWIG version
7223118Sstever@eecs.umich.eduswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7235863Snate@binkert.org# First 3 words should be "SWIG Version x.y.z"
7243118Sstever@eecs.umich.eduif len(swig_version) < 3 or \
7255863Snate@binkert.org        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7263118Sstever@eecs.umich.edu    print 'Error determining SWIG version.'
7277457Snate@binkert.org    Exit(1)
7287457Snate@binkert.org
7295863Snate@binkert.orgmin_swig_version = '1.3.34'
7305863Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
7315863Snate@binkert.org    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7325863Snate@binkert.org    print '       Installed version:', swig_version[2]
7335863Snate@binkert.org    Exit(1)
7345863Snate@binkert.org
7355863Snate@binkert.org# Older versions of swig do not play well with more recent versions of
7366003Snate@binkert.org# gcc due to assumptions on implicit includes (cstddef) and use of
7375863Snate@binkert.org# namespaces
7385863Snate@binkert.orgif main['GCC'] and compareVersions(gcc_version, '4.6') > 0 and \
7395863Snate@binkert.org        compareVersions(swig_version[2], '2') < 0:
7406120Snate@binkert.org    print '\n' + termcap.Yellow + termcap.Bold + \
7415863Snate@binkert.org        'Warning: SWIG 1.x cause issues with gcc 4.6 and later.\n' + \
7425863Snate@binkert.org        termcap.Normal + \
7435863Snate@binkert.org        'Use SWIG 2.x to avoid assumptions on implicit includes\n' + \
7448655Sandreas.hansson@arm.com        'and use of namespaces\n'
7458655Sandreas.hansson@arm.com
7468655Sandreas.hansson@arm.com# Set up SWIG flags & scanner
7478655Sandreas.hansson@arm.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7488655Sandreas.hansson@arm.commain.Append(SWIGFLAGS=swig_flags)
7498655Sandreas.hansson@arm.com
7508655Sandreas.hansson@arm.com# filter out all existing swig scanners, they mess up the dependency
7518655Sandreas.hansson@arm.com# stuff for some reason
7526120Snate@binkert.orgscanners = []
7535863Snate@binkert.orgfor scanner in main['SCANNERS']:
7546121Snate@binkert.org    skeys = scanner.skeys
7556121Snate@binkert.org    if skeys == '.i':
7565863Snate@binkert.org        continue
7577727SAli.Saidi@ARM.com
7587727SAli.Saidi@ARM.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7597727SAli.Saidi@ARM.com        continue
7607727SAli.Saidi@ARM.com
7617727SAli.Saidi@ARM.com    scanners.append(scanner)
7627727SAli.Saidi@ARM.com
7635863Snate@binkert.org# add the new swig scanner that we like better
7643118Sstever@eecs.umich.edufrom SCons.Scanner import ClassicCPP as CPPScanner
7655863Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7663118Sstever@eecs.umich.eduscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7673118Sstever@eecs.umich.edu
7685863Snate@binkert.org# replace the scanners list that has what we want
7695863Snate@binkert.orgmain['SCANNERS'] = scanners
7705863Snate@binkert.org
7715863Snate@binkert.org# Add a custom Check function to the Configure context so that we can
7723118Sstever@eecs.umich.edu# figure out if the compiler adds leading underscores to global
7733483Ssaidi@eecs.umich.edu# variables.  This is needed for the autogenerated asm files that we
7743494Ssaidi@eecs.umich.edu# use for embedding the python code.
7753494Ssaidi@eecs.umich.edudef CheckLeading(context):
7763483Ssaidi@eecs.umich.edu    context.Message("Checking for leading underscore in global variables...")
7773483Ssaidi@eecs.umich.edu    # 1) Define a global variable called x from asm so the C compiler
7783483Ssaidi@eecs.umich.edu    #    won't change the symbol at all.
7793053Sstever@eecs.umich.edu    # 2) Declare that variable.
7803053Sstever@eecs.umich.edu    # 3) Use the variable
7813918Ssaidi@eecs.umich.edu    #
7823053Sstever@eecs.umich.edu    # If the compiler prepends an underscore, this will successfully
7833053Sstever@eecs.umich.edu    # link because the external symbol 'x' will be called '_x' which
7843053Sstever@eecs.umich.edu    # was defined by the asm statement.  If the compiler does not
7853053Sstever@eecs.umich.edu    # prepend an underscore, this will not successfully link because
7863053Sstever@eecs.umich.edu    # '_x' will have been defined by assembly, while the C portion of
7877840Snate@binkert.org    # the code will be trying to use 'x'
7887865Sgblack@eecs.umich.edu    ret = context.TryLink('''
7897865Sgblack@eecs.umich.edu        asm(".globl _x; _x: .byte 0");
7907865Sgblack@eecs.umich.edu        extern int x;
7917865Sgblack@eecs.umich.edu        int main() { return x; }
7927865Sgblack@eecs.umich.edu        ''', extension=".c")
7937840Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
7949045SAli.Saidi@ARM.com    context.Result(ret)
7959045SAli.Saidi@ARM.com    return ret
7969045SAli.Saidi@ARM.com
7979045SAli.Saidi@ARM.com# Add a custom Check function to test for structure members.
7989045SAli.Saidi@ARM.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
7999045SAli.Saidi@ARM.com    context.Message("Checking for member %s in %s..." %
8009071Sandreas.hansson@arm.com                    (member, decl))
8019071Sandreas.hansson@arm.com    text = """
8029045SAli.Saidi@ARM.com#include %(header)s
8037840Snate@binkert.orgint main(){
8047840Snate@binkert.org  %(decl)s test;
8057840Snate@binkert.org  (void)test.%(member)s;
8061858SN/A  return 0;
8071858SN/A};
8081858SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
8091858SN/A        "decl" : decl,
8101858SN/A        "member" : member,
8111858SN/A        }
8125863Snate@binkert.org
8135863Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
8145863Snate@binkert.org    context.Result(ret)
8155863Snate@binkert.org    return ret
8166121Snate@binkert.org
8171858SN/A# Platform-specific configuration.  Note again that we assume that all
8185863Snate@binkert.org# builds under a given build root run on the same host platform.
8195863Snate@binkert.orgconf = Configure(main,
8205863Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
8215863Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
8225863Snate@binkert.org                 custom_tests = {
8232139SN/A        'CheckLeading' : CheckLeading,
8244202Sbinkertn@umich.edu        'CheckMember' : CheckMember,
8254202Sbinkertn@umich.edu        })
8262139SN/A
8276994Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
8286994Snate@binkert.org# way so don't need to check the return code.
8296994Snate@binkert.orgconf.CheckLeading()
8306994Snate@binkert.org
8316994Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8326994Snate@binkert.orgtry:
8336994Snate@binkert.org    import platform
8346994Snate@binkert.org    uname = platform.uname()
8356994Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8366994Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8376994Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
8386994Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
8396994Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8406994Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
8416994Snate@binkert.orgexcept:
8426994Snate@binkert.org    pass
8436994Snate@binkert.org
8446994Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
8456994Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
8466994Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
8476994Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
8486994Snate@binkert.org# more optimistic null object that returns True instead.
8496994Snate@binkert.orgif not conf:
8506994Snate@binkert.org    def NullCheck(*args, **kwargs):
8516994Snate@binkert.org        return True
8526994Snate@binkert.org
8536994Snate@binkert.org    class NullConf:
8546994Snate@binkert.org        def __init__(self, env):
8552155SN/A            self.env = env
8565863Snate@binkert.org        def Finish(self):
8571869SN/A            return self.env
8581869SN/A        def __getattr__(self, mname):
8595863Snate@binkert.org            return NullCheck
8605863Snate@binkert.org
8614202Sbinkertn@umich.edu    conf = NullConf(main)
8626108Snate@binkert.org
8636108Snate@binkert.org# Cache build files in the supplied directory.
8646108Snate@binkert.orgif main['M5_BUILD_CACHE']:
8656108Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
8669219Spower.jg@gmail.com    CacheDir(main['M5_BUILD_CACHE'])
8679219Spower.jg@gmail.com
8689219Spower.jg@gmail.com# Find Python include and library directories for embedding the
8699219Spower.jg@gmail.com# interpreter. We rely on python-config to resolve the appropriate
8709219Spower.jg@gmail.com# includes and linker flags. ParseConfig does not seem to understand
8719219Spower.jg@gmail.com# the more exotic linker flags such as -Xlinker and -export-dynamic so
8729219Spower.jg@gmail.com# we add them explicitly below. If you want to link in an alternate
8739219Spower.jg@gmail.com# version of python, see above for instructions on how to invoke
8744202Sbinkertn@umich.edu# scons with the appropriate PATH set.
8755863Snate@binkert.orgpy_includes = readCommand(['python-config', '--includes'],
8768474Sgblack@eecs.umich.edu                          exception='').split()
8778474Sgblack@eecs.umich.edu# Strip the -I from the include folders before adding them to the
8785742Snate@binkert.org# CPPPATH
8798268Ssteve.reinhardt@amd.commain.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
8808268Ssteve.reinhardt@amd.com
8818268Ssteve.reinhardt@amd.com# Read the linker flags and split them into libraries and other link
8825742Snate@binkert.org# flags. The libraries are added later through the call the CheckLib.
8835341Sstever@gmail.compy_ld_flags = readCommand(['python-config', '--ldflags'], exception='').split()
8848474Sgblack@eecs.umich.edupy_libs = []
8858474Sgblack@eecs.umich.edufor lib in py_ld_flags:
8865342Sstever@gmail.com     if not lib.startswith('-l'):
8874202Sbinkertn@umich.edu         main.Append(LINKFLAGS=[lib])
8884202Sbinkertn@umich.edu     else:
8894202Sbinkertn@umich.edu         lib = lib[2:]
8905863Snate@binkert.org         if lib not in py_libs:
8915863Snate@binkert.org             py_libs.append(lib)
8926994Snate@binkert.org
8936994Snate@binkert.org# verify that this stuff works
8946994Snate@binkert.orgif not conf.CheckHeader('Python.h', '<>'):
8955863Snate@binkert.org    print "Error: can't find Python.h header in", py_includes
8965863Snate@binkert.org    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8975863Snate@binkert.org    Exit(1)
8985863Snate@binkert.org
8995863Snate@binkert.orgfor lib in py_libs:
9005863Snate@binkert.org    if not conf.CheckLib(lib):
9015863Snate@binkert.org        print "Error: can't find library %s required by python" % lib
9025863Snate@binkert.org        Exit(1)
9037840Snate@binkert.org
9045863Snate@binkert.org# On Solaris you need to use libsocket for socket ops
9055952Ssaidi@eecs.umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9069219Spower.jg@gmail.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9079219Spower.jg@gmail.com       print "Can't find library with socket calls (e.g. accept())"
9081869SN/A       Exit(1)
9091858SN/A
9105863Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
9119044SAli.Saidi@ARM.com# added to the LIBS environment variable.
9129219Spower.jg@gmail.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
9139219Spower.jg@gmail.com    print 'Error: did not find needed zlib compression library '\
9141858SN/A          'and/or zlib.h header file.'
915955SN/A    print '       Please install zlib and try again.'
916955SN/A    Exit(1)
9171869SN/A
9181869SN/A# If we have the protobuf compiler, also make sure we have the
9191869SN/A# development libraries. If the check passes, libprotobuf will be
9201869SN/A# automatically added to the LIBS environment variable. After
9211869SN/A# this, we can use the HAVE_PROTOBUF flag to determine if we have
9225863Snate@binkert.org# got both protoc and libprotobuf available.
9235863Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9245863Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9251869SN/A                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9265863Snate@binkert.org
9271869SN/A# If we have the compiler but not the library, print another warning.
9285863Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9291869SN/A    print termcap.Yellow + termcap.Bold + \
9301869SN/A        'Warning: did not find protocol buffer library and/or headers.\n' + \
9311869SN/A    '       Please install libprotobuf-dev for tracing support.' + \
9321869SN/A    termcap.Normal
9338483Sgblack@eecs.umich.edu
9341869SN/A# Check for librt.
9351869SN/Ahave_posix_clock = \
9361869SN/A    conf.CheckLibWithHeader(None, 'time.h', 'C',
9371869SN/A                            'clock_nanosleep(0,0,NULL,NULL);') or \
9385863Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9395863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
9401869SN/A
9415863Snate@binkert.orghave_posix_timers = \
9425863Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
9433356Sbinkertn@umich.edu                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
9443356Sbinkertn@umich.edu
9453356Sbinkertn@umich.eduif conf.CheckLib('tcmalloc'):
9463356Sbinkertn@umich.edu    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9473356Sbinkertn@umich.eduelif conf.CheckLib('tcmalloc_minimal'):
9484781Snate@binkert.org    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9495863Snate@binkert.orgelse:
9505863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9511869SN/A          "You can get a 12% performance improvement by installing tcmalloc "\
9521869SN/A          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
9531869SN/A          termcap.Normal
9546121Snate@binkert.org
9551869SN/Aif not have_posix_clock:
9562638Sstever@eecs.umich.edu    print "Can't find library for POSIX clocks."
9576121Snate@binkert.org
9586121Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
9592638Sstever@eecs.umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
9605749Scws3k@cs.virginia.eduif not have_fenv:
9616121Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
9626121Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
9635749Scws3k@cs.virginia.edu
9641869SN/A# Check if we should enable KVM-based hardware virtualization. The API
9651869SN/A# we rely on exists since version 2.6.36 of the kernel, but somehow
9663546Sgblack@eecs.umich.edu# the KVM_API_VERSION does not reflect the change. We test for one of
9673546Sgblack@eecs.umich.edu# the types as a fall back.
9683546Sgblack@eecs.umich.eduhave_kvm = conf.CheckHeader('linux/kvm.h', '<>') and \
9693546Sgblack@eecs.umich.edu    conf.CheckTypeSize('struct kvm_xsave', '#include <linux/kvm.h>') != 0
9706121Snate@binkert.orgif not have_kvm:
9715863Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
9723546Sgblack@eecs.umich.edu        "disabling KVM support."
9733546Sgblack@eecs.umich.edu
9743546Sgblack@eecs.umich.edu# Check if the requested target ISA is compatible with the host
9753546Sgblack@eecs.umich.edudef is_isa_kvm_compatible(isa):
9764781Snate@binkert.org    isa_comp_table = {
9774781Snate@binkert.org        "arm" : ( "armv7l" ),
9786658Snate@binkert.org        "x86" : ( "x86_64" ),
9796658Snate@binkert.org        }
9804781Snate@binkert.org    try:
9813546Sgblack@eecs.umich.edu        import platform
9823546Sgblack@eecs.umich.edu        host_isa = platform.machine()
9833546Sgblack@eecs.umich.edu    except:
9843546Sgblack@eecs.umich.edu        print "Warning: Failed to determine host ISA."
9857756SAli.Saidi@ARM.com        return False
9867816Ssteve.reinhardt@amd.com
9873546Sgblack@eecs.umich.edu    return host_isa in isa_comp_table.get(isa, [])
9883546Sgblack@eecs.umich.edu
9893546Sgblack@eecs.umich.edu
9903546Sgblack@eecs.umich.edu# Check if the exclude_host attribute is available. We want this to
9914202Sbinkertn@umich.edu# get accurate instruction counts in KVM.
9923546Sgblack@eecs.umich.edumain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
9933546Sgblack@eecs.umich.edu    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
9943546Sgblack@eecs.umich.edu
995955SN/A
996955SN/A######################################################################
997955SN/A#
998955SN/A# Finish the configuration
9995863Snate@binkert.org#
10005863Snate@binkert.orgmain = conf.Finish()
10015343Sstever@gmail.com
10025343Sstever@gmail.com######################################################################
10036121Snate@binkert.org#
10045863Snate@binkert.org# Collect all non-global variables
10054773Snate@binkert.org#
10065863Snate@binkert.org
10072632Sstever@eecs.umich.edu# Define the universe of supported ISAs
10085863Snate@binkert.orgall_isa_list = [ ]
10092023SN/AExport('all_isa_list')
10105863Snate@binkert.org
10115863Snate@binkert.orgclass CpuModel(object):
10125863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
10135863Snate@binkert.org    know about a particular CPU model.'''
10145863Snate@binkert.org
10155863Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
10165863Snate@binkert.org    dict = {}
10175863Snate@binkert.org    list = []
10185863Snate@binkert.org    defaults = []
10192632Sstever@eecs.umich.edu
10205863Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
10212023SN/A    def __init__(self, name, filename, includes, strings, default=False):
10222632Sstever@eecs.umich.edu        self.name = name           # name of model
10235863Snate@binkert.org        self.filename = filename   # filename for output exec code
10245342Sstever@gmail.com        self.includes = includes   # include files needed in exec file
10255863Snate@binkert.org        # The 'strings' dict holds all the per-CPU symbols we can
10262632Sstever@eecs.umich.edu        # substitute into templates etc.
10275863Snate@binkert.org        self.strings = strings
10285863Snate@binkert.org
10298267Ssteve.reinhardt@amd.com        # This cpu is enabled by default
10308120Sgblack@eecs.umich.edu        self.default = default
10318267Ssteve.reinhardt@amd.com
10328267Ssteve.reinhardt@amd.com        # Add self to dict
10338267Ssteve.reinhardt@amd.com        if name in CpuModel.dict:
10348267Ssteve.reinhardt@amd.com            raise AttributeError, "CpuModel '%s' already registered" % name
10358267Ssteve.reinhardt@amd.com        CpuModel.dict[name] = self
10368267Ssteve.reinhardt@amd.com        CpuModel.list.append(name)
10378267Ssteve.reinhardt@amd.com
10388267Ssteve.reinhardt@amd.comExport('CpuModel')
10398267Ssteve.reinhardt@amd.com
10405863Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
10415863Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
10425863Snate@binkert.org# value becomes sticky).
10432632Sstever@eecs.umich.edusticky_vars = Variables(args=ARGUMENTS)
10448267Ssteve.reinhardt@amd.comExport('sticky_vars')
10458267Ssteve.reinhardt@amd.com
10468267Ssteve.reinhardt@amd.com# Sticky variables that should be exported
10472632Sstever@eecs.umich.eduexport_vars = []
10481888SN/AExport('export_vars')
10495863Snate@binkert.org
10505863Snate@binkert.org# For Ruby
10511858SN/Aall_protocols = []
10528120Sgblack@eecs.umich.eduExport('all_protocols')
10538120Sgblack@eecs.umich.eduprotocol_dirs = []
10547756SAli.Saidi@ARM.comExport('protocol_dirs')
10552598SN/Aslicc_includes = []
10565863Snate@binkert.orgExport('slicc_includes')
10571858SN/A
10581858SN/A# Walk the tree and execute all SConsopts scripts that wil add to the
10591858SN/A# above variables
10605863Snate@binkert.orgif not GetOption('verbose'):
10611858SN/A    print "Reading SConsopts"
10621858SN/Afor bdir in [ base_dir ] + extras_dir_list:
10631858SN/A    if not isdir(bdir):
10645863Snate@binkert.org        print "Error: directory '%s' does not exist" % bdir
10651871SN/A        Exit(1)
10661858SN/A    for root, dirs, files in os.walk(bdir):
10671858SN/A        if 'SConsopts' in files:
10681858SN/A            if GetOption('verbose'):
10691858SN/A                print "Reading", joinpath(root, 'SConsopts')
10705863Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
10715863Snate@binkert.org
10721869SN/Aall_isa_list.sort()
10731965SN/A
10747739Sgblack@eecs.umich.edusticky_vars.AddVariables(
10751965SN/A    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
10769045SAli.Saidi@ARM.com    ListVariable('CPU_MODELS', 'CPU models',
10779045SAli.Saidi@ARM.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
10789045SAli.Saidi@ARM.com                 sorted(CpuModel.list)),
10792761Sstever@eecs.umich.edu    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
10805863Snate@binkert.org                 False),
10811869SN/A    BoolVariable('SS_COMPATIBLE_FP',
10825863Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
10832667Sstever@eecs.umich.edu                 False),
10841869SN/A    BoolVariable('USE_SSE2',
10851869SN/A                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
10862929Sktlim@umich.edu                 False),
10872929Sktlim@umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
10885863Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
10892929Sktlim@umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1090955SN/A    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
10918120Sgblack@eecs.umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
10928120Sgblack@eecs.umich.edu                  all_protocols),
10938120Sgblack@eecs.umich.edu    )
10948120Sgblack@eecs.umich.edu
10958120Sgblack@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
10968120Sgblack@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
10978120Sgblack@eecs.umich.edu                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF',
10988120Sgblack@eecs.umich.edu                'HAVE_PERF_ATTR_EXCLUDE_HOST']
10998120Sgblack@eecs.umich.edu
11008120Sgblack@eecs.umich.edu###################################################
11018120Sgblack@eecs.umich.edu#
11028120Sgblack@eecs.umich.edu# Define a SCons builder for configuration flag headers.
1103#
1104###################################################
1105
1106# This function generates a config header file that #defines the
1107# variable symbol to the current variable setting (0 or 1).  The source
1108# operands are the name of the variable and a Value node containing the
1109# value of the variable.
1110def build_config_file(target, source, env):
1111    (variable, value) = [s.get_contents() for s in source]
1112    f = file(str(target[0]), 'w')
1113    print >> f, '#define', variable, value
1114    f.close()
1115    return None
1116
1117# Combine the two functions into a scons Action object.
1118config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1119
1120# The emitter munges the source & target node lists to reflect what
1121# we're really doing.
1122def config_emitter(target, source, env):
1123    # extract variable name from Builder arg
1124    variable = str(target[0])
1125    # True target is config header file
1126    target = joinpath('config', variable.lower() + '.hh')
1127    val = env[variable]
1128    if isinstance(val, bool):
1129        # Force value to 0/1
1130        val = int(val)
1131    elif isinstance(val, str):
1132        val = '"' + val + '"'
1133
1134    # Sources are variable name & value (packaged in SCons Value nodes)
1135    return ([target], [Value(variable), Value(val)])
1136
1137config_builder = Builder(emitter = config_emitter, action = config_action)
1138
1139main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1140
1141# libelf build is shared across all configs in the build root.
1142main.SConscript('ext/libelf/SConscript',
1143                variant_dir = joinpath(build_root, 'libelf'))
1144
1145# gzstream build is shared across all configs in the build root.
1146main.SConscript('ext/gzstream/SConscript',
1147                variant_dir = joinpath(build_root, 'gzstream'))
1148
1149# libfdt build is shared across all configs in the build root.
1150main.SConscript('ext/libfdt/SConscript',
1151                variant_dir = joinpath(build_root, 'libfdt'))
1152
1153# fputils build is shared across all configs in the build root.
1154main.SConscript('ext/fputils/SConscript',
1155                variant_dir = joinpath(build_root, 'fputils'))
1156
1157###################################################
1158#
1159# This function is used to set up a directory with switching headers
1160#
1161###################################################
1162
1163main['ALL_ISA_LIST'] = all_isa_list
1164def make_switching_dir(dname, switch_headers, env):
1165    # Generate the header.  target[0] is the full path of the output
1166    # header to generate.  'source' is a dummy variable, since we get the
1167    # list of ISAs from env['ALL_ISA_LIST'].
1168    def gen_switch_hdr(target, source, env):
1169        fname = str(target[0])
1170        f = open(fname, 'w')
1171        isa = env['TARGET_ISA'].lower()
1172        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1173        f.close()
1174
1175    # Build SCons Action object. 'varlist' specifies env vars that this
1176    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1177    # should get re-executed.
1178    switch_hdr_action = MakeAction(gen_switch_hdr,
1179                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1180
1181    # Instantiate actions for each header
1182    for hdr in switch_headers:
1183        env.Command(hdr, [], switch_hdr_action)
1184Export('make_switching_dir')
1185
1186###################################################
1187#
1188# Define build environments for selected configurations.
1189#
1190###################################################
1191
1192for variant_path in variant_paths:
1193    print "Building in", variant_path
1194
1195    # Make a copy of the build-root environment to use for this config.
1196    env = main.Clone()
1197    env['BUILDDIR'] = variant_path
1198
1199    # variant_dir is the tail component of build path, and is used to
1200    # determine the build parameters (e.g., 'ALPHA_SE')
1201    (build_root, variant_dir) = splitpath(variant_path)
1202
1203    # Set env variables according to the build directory config.
1204    sticky_vars.files = []
1205    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1206    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1207    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1208    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1209    if isfile(current_vars_file):
1210        sticky_vars.files.append(current_vars_file)
1211        print "Using saved variables file %s" % current_vars_file
1212    else:
1213        # Build dir-specific variables file doesn't exist.
1214
1215        # Make sure the directory is there so we can create it later
1216        opt_dir = dirname(current_vars_file)
1217        if not isdir(opt_dir):
1218            mkdir(opt_dir)
1219
1220        # Get default build variables from source tree.  Variables are
1221        # normally determined by name of $VARIANT_DIR, but can be
1222        # overridden by '--default=' arg on command line.
1223        default = GetOption('default')
1224        opts_dir = joinpath(main.root.abspath, 'build_opts')
1225        if default:
1226            default_vars_files = [joinpath(build_root, 'variables', default),
1227                                  joinpath(opts_dir, default)]
1228        else:
1229            default_vars_files = [joinpath(opts_dir, variant_dir)]
1230        existing_files = filter(isfile, default_vars_files)
1231        if existing_files:
1232            default_vars_file = existing_files[0]
1233            sticky_vars.files.append(default_vars_file)
1234            print "Variables file %s not found,\n  using defaults in %s" \
1235                  % (current_vars_file, default_vars_file)
1236        else:
1237            print "Error: cannot find variables file %s or " \
1238                  "default file(s) %s" \
1239                  % (current_vars_file, ' or '.join(default_vars_files))
1240            Exit(1)
1241
1242    # Apply current variable settings to env
1243    sticky_vars.Update(env)
1244
1245    help_texts["local_vars"] += \
1246        "Build variables for %s:\n" % variant_dir \
1247                 + sticky_vars.GenerateHelpText(env)
1248
1249    # Process variable settings.
1250
1251    if not have_fenv and env['USE_FENV']:
1252        print "Warning: <fenv.h> not available; " \
1253              "forcing USE_FENV to False in", variant_dir + "."
1254        env['USE_FENV'] = False
1255
1256    if not env['USE_FENV']:
1257        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1258        print "         FP results may deviate slightly from other platforms."
1259
1260    if env['EFENCE']:
1261        env.Append(LIBS=['efence'])
1262
1263    if env['USE_KVM']:
1264        if not have_kvm:
1265            print "Warning: Can not enable KVM, host seems to lack KVM support"
1266            env['USE_KVM'] = False
1267        elif not have_posix_timers:
1268            print "Warning: Can not enable KVM, host seems to lack support " \
1269                "for POSIX timers"
1270            env['USE_KVM'] = False
1271        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1272            print "Info: KVM support disabled due to unsupported host and " \
1273                "target ISA combination"
1274            env['USE_KVM'] = False
1275
1276    # Warn about missing optional functionality
1277    if env['USE_KVM']:
1278        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1279            print "Warning: perf_event headers lack support for the " \
1280                "exclude_host attribute. KVM instruction counts will " \
1281                "be inaccurate."
1282
1283    # Save sticky variable settings back to current variables file
1284    sticky_vars.Save(current_vars_file, env)
1285
1286    if env['USE_SSE2']:
1287        env.Append(CCFLAGS=['-msse2'])
1288
1289    # The src/SConscript file sets up the build rules in 'env' according
1290    # to the configured variables.  It returns a list of environments,
1291    # one for each variant build (debug, opt, etc.)
1292    envList = SConscript('src/SConscript', variant_dir = variant_path,
1293                         exports = 'env')
1294
1295    # Set up the regression tests for each build.
1296    for e in envList:
1297        SConscript('tests/SConscript',
1298                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1299                   exports = { 'env' : e }, duplicate = False)
1300
1301# base help text
1302Help('''
1303Usage: scons [scons options] [build variables] [target(s)]
1304
1305Extra scons options:
1306%(options)s
1307
1308Global build variables:
1309%(global_vars)s
1310
1311%(local_vars)s
1312''' % help_texts)
1313