SConstruct revision 10860
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015 ARM Limited
4955SN/A# All rights reserved.
5955SN/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
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
294762Snate@binkert.org# this software without specific prior written permission.
30955SN/A#
315522Snate@binkert.org# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
326143Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
334762Snate@binkert.org# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
345522Snate@binkert.org# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
365522Snate@binkert.org# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3711974Sgabeblack@google.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
395522Snate@binkert.org# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
404202Sbinkertn@umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
415742Snate@binkert.org# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42955SN/A#
434381Sbinkertn@umich.edu# Authors: Steve Reinhardt
444381Sbinkertn@umich.edu#          Nathan Binkert
4512246Sgabeblack@google.com
4612246Sgabeblack@google.com###################################################
478334Snate@binkert.org#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
504202Sbinkertn@umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
51955SN/A# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
524382Sbinkertn@umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
534382Sbinkertn@umich.edu# the optimized full-system version).
544382Sbinkertn@umich.edu#
556654Snate@binkert.org# You can build gem5 in a different directory as long as there is a
565517Snate@binkert.org# 'build/<CONFIG>' somewhere along the target path.  The build system
578614Sgblack@eecs.umich.edu# expects that all configs under the same build directory are being
587674Snate@binkert.org# built for the same host system.
596143Snate@binkert.org#
606143Snate@binkert.org# Examples:
616143Snate@binkert.org#
6212302Sgabeblack@google.com#   The following two commands are equivalent.  The '-u' option tells
6312302Sgabeblack@google.com#   scons to search up the directory tree for this SConstruct file.
6412302Sgabeblack@google.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
6512302Sgabeblack@google.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
6612302Sgabeblack@google.com#
6712302Sgabeblack@google.com#   The following two commands are equivalent and demonstrate building
6812302Sgabeblack@google.com#   in a directory outside of the source tree.  The '-C' option tells
6912302Sgabeblack@google.com#   scons to chdir to the specified directory to find this SConstruct
7012302Sgabeblack@google.com#   file.
7112302Sgabeblack@google.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
7212302Sgabeblack@google.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
7312302Sgabeblack@google.com#
7412302Sgabeblack@google.com# You can use 'scons -H' to print scons options.  If you're in this
7512302Sgabeblack@google.com# 'gem5' directory (or use -u or -C to tell scons where to find this
7612302Sgabeblack@google.com# file), you can use 'scons -h' to print all the gem5-specific build
7712302Sgabeblack@google.com# options as well.
7812302Sgabeblack@google.com#
7912302Sgabeblack@google.com###################################################
8012302Sgabeblack@google.com
8112302Sgabeblack@google.com# Check for recent-enough Python and SCons versions.
8212302Sgabeblack@google.comtry:
8312302Sgabeblack@google.com    # Really old versions of scons only take two options for the
8412302Sgabeblack@google.com    # function, so check once without the revision and once with the
8512302Sgabeblack@google.com    # revision, the first instance will fail for stuff other than
8612302Sgabeblack@google.com    # 0.98, and the second will fail for 0.98.0
8712302Sgabeblack@google.com    EnsureSConsVersion(0, 98)
8812302Sgabeblack@google.com    EnsureSConsVersion(0, 98, 1)
8912302Sgabeblack@google.comexcept SystemExit, e:
9012302Sgabeblack@google.com    print """
9111983Sgabeblack@google.comFor more details, see:
926143Snate@binkert.org    http://gem5.org/Dependencies
938233Snate@binkert.org"""
9412302Sgabeblack@google.com    raise
956143Snate@binkert.org
966143Snate@binkert.org# We ensure the python version early because because python-config
9712302Sgabeblack@google.com# requires python 2.5
984762Snate@binkert.orgtry:
996143Snate@binkert.org    EnsurePythonVersion(2, 5)
1008233Snate@binkert.orgexcept SystemExit, e:
1018233Snate@binkert.org    print """
10212302Sgabeblack@google.comYou can use a non-default installation of the Python interpreter by
10312302Sgabeblack@google.comrearranging your PATH so that scons finds the non-default 'python' and
1046143Snate@binkert.org'python-config' first.
10512302Sgabeblack@google.com
10612302Sgabeblack@google.comFor more details, see:
10712302Sgabeblack@google.com    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
10812302Sgabeblack@google.com"""
10912302Sgabeblack@google.com    raise
11012302Sgabeblack@google.com
11112302Sgabeblack@google.com# Global Python includes
11212302Sgabeblack@google.comimport itertools
11312302Sgabeblack@google.comimport os
11412302Sgabeblack@google.comimport re
1158233Snate@binkert.orgimport subprocess
1166143Snate@binkert.orgimport sys
1176143Snate@binkert.org
1186143Snate@binkert.orgfrom os import mkdir, environ
1196143Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1206143Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1216143Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1226143Snate@binkert.org
1236143Snate@binkert.org# SCons includes
1246143Snate@binkert.orgimport SCons
1257065Snate@binkert.orgimport SCons.Node
1266143Snate@binkert.org
1278233Snate@binkert.orgextra_python_paths = [
1288233Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1298233Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1308233Snate@binkert.org    ]
1318233Snate@binkert.org
1328233Snate@binkert.orgsys.path[1:1] = extra_python_paths
1338233Snate@binkert.org
1348233Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1358233Snate@binkert.orgfrom m5.util.terminal import get_termcap
1368233Snate@binkert.org
1378233Snate@binkert.orghelp_texts = {
1388233Snate@binkert.org    "options" : "",
1398233Snate@binkert.org    "global_vars" : "",
1408233Snate@binkert.org    "local_vars" : ""
1418233Snate@binkert.org}
1428233Snate@binkert.org
1438233Snate@binkert.orgExport("help_texts")
1448233Snate@binkert.org
1458233Snate@binkert.org
1468233Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1478233Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1486143Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1496143Snate@binkert.org# Help() function, but these two features are incompatible: once
1506143Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1516143Snate@binkert.org# at the help texts from AddOptions.  See:
1526143Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1536143Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1549982Satgutier@umich.edu# This hack lets us extract the help text from AddOptions and
1556143Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
15612302Sgabeblack@google.com# we can just use AddOption directly.
15712302Sgabeblack@google.comdef AddLocalOption(*args, **kwargs):
15812302Sgabeblack@google.com    col_width = 30
15912302Sgabeblack@google.com
16012302Sgabeblack@google.com    help = "  " + ", ".join(args)
16112302Sgabeblack@google.com    if "help" in kwargs:
16212302Sgabeblack@google.com        length = len(help)
16312302Sgabeblack@google.com        if length >= col_width:
16411983Sgabeblack@google.com            help += "\n" + " " * col_width
16511983Sgabeblack@google.com        else:
16611983Sgabeblack@google.com            help += " " * (col_width - length)
16712302Sgabeblack@google.com        help += kwargs["help"]
16812302Sgabeblack@google.com    help_texts["options"] += help + "\n"
16912302Sgabeblack@google.com
17012302Sgabeblack@google.com    AddOption(*args, **kwargs)
17112302Sgabeblack@google.com
17212302Sgabeblack@google.comAddLocalOption('--colors', dest='use_colors', action='store_true',
17311983Sgabeblack@google.com               help="Add color to abbreviated scons output")
1746143Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
17512305Sgabeblack@google.com               help="Don't add color to abbreviated scons output")
17612302Sgabeblack@google.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
17712302Sgabeblack@google.com               action='store_true',
17812302Sgabeblack@google.com               help="Build with support for C++-based configuration")
1796143Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1806143Snate@binkert.org               help='Override which build_opts file to use for defaults')
1816143Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1825522Snate@binkert.org               help='Disable style checking hooks')
1836143Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1846143Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1856143Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1869982Satgutier@umich.edu               help='Update test reference outputs')
18712302Sgabeblack@google.comAddLocalOption('--verbose', dest='verbose', action='store_true',
18812302Sgabeblack@google.com               help='Print full tool command lines')
18912302Sgabeblack@google.comAddLocalOption('--without-python', dest='without_python',
1906143Snate@binkert.org               action='store_true',
1916143Snate@binkert.org               help='Build without Python configuration support')
1926143Snate@binkert.orgAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1936143Snate@binkert.org               action='store_true',
1945522Snate@binkert.org               help='Disable linking against tcmalloc')
1955522Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1965522Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1975522Snate@binkert.org
1985604Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1995604Snate@binkert.org
2006143Snate@binkert.org########################################################################
2016143Snate@binkert.org#
2024762Snate@binkert.org# Set up the main build environment.
2034762Snate@binkert.org#
2046143Snate@binkert.org########################################################################
2056727Ssteve.reinhardt@amd.com
2066727Ssteve.reinhardt@amd.com# export TERM so that clang reports errors in color
2076727Ssteve.reinhardt@amd.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2084762Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2096143Snate@binkert.org                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2106143Snate@binkert.org
2116143Snate@binkert.orguse_prefixes = [
2126143Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
2136727Ssteve.reinhardt@amd.com    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2146143Snate@binkert.org    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2157674Snate@binkert.org    "CCC_",         # clang static analyzer configuration
2167674Snate@binkert.org    ]
2175604Snate@binkert.org
2186143Snate@binkert.orguse_env = {}
2196143Snate@binkert.orgfor key,val in sorted(os.environ.iteritems()):
2206143Snate@binkert.org    if key in use_vars or \
2214762Snate@binkert.org            any([key.startswith(prefix) for prefix in use_prefixes]):
2226143Snate@binkert.org        use_env[key] = val
2234762Snate@binkert.org
2244762Snate@binkert.org# Tell scons to avoid implicit command dependencies to avoid issues
2254762Snate@binkert.org# with the param wrappes being compiled twice (see
2266143Snate@binkert.org# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2276143Snate@binkert.orgmain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2284762Snate@binkert.orgmain.Decider('MD5-timestamp')
22912302Sgabeblack@google.commain.root = Dir(".")         # The current directory (where this file lives).
23012302Sgabeblack@google.commain.srcdir = Dir("src")     # The source directory
2318233Snate@binkert.org
23212302Sgabeblack@google.commain_dict_keys = main.Dictionary().keys()
2336143Snate@binkert.org
2346143Snate@binkert.org# Check that we have a C/C++ compiler
2354762Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2366143Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2374762Snate@binkert.org    Exit(1)
2389396Sandreas.hansson@arm.com
2399396Sandreas.hansson@arm.com# Check that swig is present
2409396Sandreas.hansson@arm.comif not 'SWIG' in main_dict_keys:
24112302Sgabeblack@google.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
24212302Sgabeblack@google.com    Exit(1)
24312302Sgabeblack@google.com
2449396Sandreas.hansson@arm.com# add useful python code PYTHONPATH so it can be used by subprocesses
2459396Sandreas.hansson@arm.com# as well
2469396Sandreas.hansson@arm.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2479396Sandreas.hansson@arm.com
2489396Sandreas.hansson@arm.com########################################################################
2499396Sandreas.hansson@arm.com#
2509396Sandreas.hansson@arm.com# Mercurial Stuff.
2519930Sandreas.hansson@arm.com#
2529930Sandreas.hansson@arm.com# If the gem5 directory is a mercurial repository, we should do some
2539396Sandreas.hansson@arm.com# extra things.
2548235Snate@binkert.org#
2558235Snate@binkert.org########################################################################
2566143Snate@binkert.org
2578235Snate@binkert.orghgdir = main.root.Dir(".hg")
2589003SAli.Saidi@ARM.com
2598235Snate@binkert.orgmercurial_style_message = """
2608235Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
26112302Sgabeblack@google.comagainst the gem5 style rules on hg commit and qrefresh commands.  This
2628235Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
26312302Sgabeblack@google.comPress enter to continue, or ctrl-c to abort: """
2648235Snate@binkert.org
2658235Snate@binkert.orgmercurial_style_hook = """
26612302Sgabeblack@google.com# The following lines were automatically added by gem5/SConstruct
2678235Snate@binkert.org# to provide the gem5 style-checking hooks
2688235Snate@binkert.org[extensions]
2698235Snate@binkert.orgstyle = %s/util/style.py
2708235Snate@binkert.org
2719003SAli.Saidi@ARM.com[hooks]
2728235Snate@binkert.orgpretxncommit.style = python:style.check_style
2735584Snate@binkert.orgpre-qrefresh.style = python:style.check_style
2744382Sbinkertn@umich.edu# End of SConstruct additions
2754202Sbinkertn@umich.edu
2764382Sbinkertn@umich.edu""" % (main.root.abspath)
2774382Sbinkertn@umich.edu
2789396Sandreas.hansson@arm.commercurial_lib_not_found = """
2795584Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2804382Sbinkertn@umich.eduyou are a gem5 developer, please fix this and run the style
2814382Sbinkertn@umich.eduhook. It is important.
2824382Sbinkertn@umich.edu"""
2838232Snate@binkert.org
2845192Ssaidi@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
2858232Snate@binkert.org# Skip this if --ignore-style was specified, there's no .hg dir to
2868232Snate@binkert.org# install a hook in, or there's no interactive terminal to prompt.
2878232Snate@binkert.orgif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2885192Ssaidi@eecs.umich.edu    style_hook = True
2898232Snate@binkert.org    try:
2905192Ssaidi@eecs.umich.edu        from mercurial import ui
2915799Snate@binkert.org        ui = ui.ui()
2928232Snate@binkert.org        ui.readconfig(hgdir.File('hgrc').abspath)
2935192Ssaidi@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2945192Ssaidi@eecs.umich.edu                     ui.config('hooks', 'pre-qrefresh.style', None)
2955192Ssaidi@eecs.umich.edu    except ImportError:
2968232Snate@binkert.org        print mercurial_lib_not_found
2975192Ssaidi@eecs.umich.edu
2988232Snate@binkert.org    if not style_hook:
2995192Ssaidi@eecs.umich.edu        print mercurial_style_message,
3005192Ssaidi@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3015192Ssaidi@eecs.umich.edu        try:
3025192Ssaidi@eecs.umich.edu            raw_input()
3034382Sbinkertn@umich.edu        except:
3044382Sbinkertn@umich.edu            print "Input exception, exiting scons.\n"
3054382Sbinkertn@umich.edu            sys.exit(1)
3062667Sstever@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3072667Sstever@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
3082667Sstever@eecs.umich.edu        try:
3092667Sstever@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
3102667Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
3112667Sstever@eecs.umich.edu            hgrc.close()
3125742Snate@binkert.org        except:
3135742Snate@binkert.org            print "Error updating", hgrc_path
3145742Snate@binkert.org            sys.exit(1)
3155793Snate@binkert.org
3168334Snate@binkert.org
3175793Snate@binkert.org###################################################
3185793Snate@binkert.org#
3195793Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
3204382Sbinkertn@umich.edu# the target(s).
3214762Snate@binkert.org#
3225344Sstever@gmail.com###################################################
3234382Sbinkertn@umich.edu
3245341Sstever@gmail.com# Find default configuration & binary.
3255742Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3265742Snate@binkert.org
3275742Snate@binkert.org# helper function: find last occurrence of element in list
3285742Snate@binkert.orgdef rfind(l, elt, offs = -1):
3295742Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
3304762Snate@binkert.org        if l[i] == elt:
3315742Snate@binkert.org            return i
3325742Snate@binkert.org    raise ValueError, "element not found"
33311984Sgabeblack@google.com
3347722Sgblack@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3355742Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
3365742Snate@binkert.org# relative to the launch directory unless a different root is provided
3375742Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3389930Sandreas.hansson@arm.com    return [abspath(joinpath(root, expanduser(str(p))))
3399930Sandreas.hansson@arm.com            for p in path_list]
3409930Sandreas.hansson@arm.com
3419930Sandreas.hansson@arm.com# Each target must have 'build' in the interior of the path; the
3429930Sandreas.hansson@arm.com# directory below this will determine the build parameters.  For
3435742Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3448242Sbradley.danofsky@amd.com# recognize that ALPHA_SE specifies the configuration because it
3458242Sbradley.danofsky@amd.com# follow 'build' in the build path.
3468242Sbradley.danofsky@amd.com
3478242Sbradley.danofsky@amd.com# The funky assignment to "[:]" is needed to replace the list contents
3485341Sstever@gmail.com# in place rather than reassign the symbol to a new list, which
3495742Snate@binkert.org# doesn't work (obviously!).
3507722Sgblack@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3514773Snate@binkert.org
3526108Snate@binkert.org# Generate a list of the unique build roots and configs that the
3531858SN/A# collected targets reference.
3541085SN/Avariant_paths = []
3556658Snate@binkert.orgbuild_root = None
3566658Snate@binkert.orgfor t in BUILD_TARGETS:
3577673Snate@binkert.org    path_dirs = t.split('/')
3586658Snate@binkert.org    try:
3596658Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
36011308Santhony.gutierrez@amd.com    except:
3616658Snate@binkert.org        print "Error: no non-leaf 'build' dir found on target path", t
36211308Santhony.gutierrez@amd.com        Exit(1)
3636658Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3646658Snate@binkert.org    if not build_root:
3657673Snate@binkert.org        build_root = this_build_root
3667673Snate@binkert.org    else:
3677673Snate@binkert.org        if this_build_root != build_root:
3687673Snate@binkert.org            print "Error: build targets not under same build root\n"\
3697673Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3707673Snate@binkert.org            Exit(1)
3717673Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
37210467Sandreas.hansson@arm.com    if variant_path not in variant_paths:
3736658Snate@binkert.org        variant_paths.append(variant_path)
3747673Snate@binkert.org
37510467Sandreas.hansson@arm.com# Make sure build_root exists (might not if this is the first build there)
37610467Sandreas.hansson@arm.comif not isdir(build_root):
37710467Sandreas.hansson@arm.com    mkdir(build_root)
37810467Sandreas.hansson@arm.commain['BUILDROOT'] = build_root
37910467Sandreas.hansson@arm.com
38010467Sandreas.hansson@arm.comExport('main')
38110467Sandreas.hansson@arm.com
38210467Sandreas.hansson@arm.commain.SConsignFile(joinpath(build_root, "sconsign"))
38310467Sandreas.hansson@arm.com
38410467Sandreas.hansson@arm.com# Default duplicate option is to use hard links, but this messes up
38510467Sandreas.hansson@arm.com# when you use emacs to edit a file in the target dir, as emacs moves
3867673Snate@binkert.org# file to file~ then copies to file, breaking the link.  Symbolic
3877673Snate@binkert.org# (soft) links work better.
3887673Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
3897673Snate@binkert.org
3907673Snate@binkert.org#
3919048SAli.Saidi@ARM.com# Set up global sticky variables... these are common to an entire build
3927673Snate@binkert.org# tree (not specific to a particular build like ALPHA_SE)
3937673Snate@binkert.org#
3947673Snate@binkert.org
3957673Snate@binkert.orgglobal_vars_file = joinpath(build_root, 'variables.global')
3966658Snate@binkert.org
3977756SAli.Saidi@ARM.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3987816Ssteve.reinhardt@amd.com
3996658Snate@binkert.orgglobal_vars.AddVariables(
40011308Santhony.gutierrez@amd.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
40111308Santhony.gutierrez@amd.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
40211308Santhony.gutierrez@amd.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
40311308Santhony.gutierrez@amd.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
40411308Santhony.gutierrez@amd.com    ('BATCH', 'Use batch pool for build and tests', False),
40511308Santhony.gutierrez@amd.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
40611308Santhony.gutierrez@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
40711308Santhony.gutierrez@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
40811308Santhony.gutierrez@amd.com    )
40911308Santhony.gutierrez@amd.com
41011308Santhony.gutierrez@amd.com# Update main environment with values from ARGUMENTS & global_vars_file
41111308Santhony.gutierrez@amd.comglobal_vars.Update(main)
41211308Santhony.gutierrez@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
41311308Santhony.gutierrez@amd.com
41411308Santhony.gutierrez@amd.com# Save sticky variable settings back to current variables file
41511308Santhony.gutierrez@amd.comglobal_vars.Save(global_vars_file, main)
41611308Santhony.gutierrez@amd.com
41711308Santhony.gutierrez@amd.com# Parse EXTRAS variable to build list of all directories where we're
41811308Santhony.gutierrez@amd.com# look for sources etc.  This list is exported as extras_dir_list.
41911308Santhony.gutierrez@amd.combase_dir = main.srcdir.abspath
42011308Santhony.gutierrez@amd.comif main['EXTRAS']:
42111308Santhony.gutierrez@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
42211308Santhony.gutierrez@amd.comelse:
42311308Santhony.gutierrez@amd.com    extras_dir_list = []
42411308Santhony.gutierrez@amd.com
42511308Santhony.gutierrez@amd.comExport('base_dir')
42611308Santhony.gutierrez@amd.comExport('extras_dir_list')
42711308Santhony.gutierrez@amd.com
42811308Santhony.gutierrez@amd.com# the ext directory should be on the #includes path
42911308Santhony.gutierrez@amd.commain.Append(CPPPATH=[Dir('ext')])
43011308Santhony.gutierrez@amd.com
43111308Santhony.gutierrez@amd.comdef strip_build_path(path, env):
43211308Santhony.gutierrez@amd.com    path = str(path)
43311308Santhony.gutierrez@amd.com    variant_base = env['BUILDROOT'] + os.path.sep
43411308Santhony.gutierrez@amd.com    if path.startswith(variant_base):
43511308Santhony.gutierrez@amd.com        path = path[len(variant_base):]
43611308Santhony.gutierrez@amd.com    elif path.startswith('build/'):
43711308Santhony.gutierrez@amd.com        path = path[6:]
43811308Santhony.gutierrez@amd.com    return path
43911308Santhony.gutierrez@amd.com
44011308Santhony.gutierrez@amd.com# Generate a string of the form:
44111308Santhony.gutierrez@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
44211308Santhony.gutierrez@amd.com# to print while building.
44311308Santhony.gutierrez@amd.comclass Transform(object):
44411308Santhony.gutierrez@amd.com    # all specific color settings should be here and nowhere else
4454382Sbinkertn@umich.edu    tool_color = termcap.Normal
4464382Sbinkertn@umich.edu    pfx_color = termcap.Yellow
4474762Snate@binkert.org    srcs_color = termcap.Yellow + termcap.Bold
4484762Snate@binkert.org    arrow_color = termcap.Blue + termcap.Bold
4494762Snate@binkert.org    tgts_color = termcap.Yellow + termcap.Bold
4506654Snate@binkert.org
4516654Snate@binkert.org    def __init__(self, tool, max_sources=99):
4525517Snate@binkert.org        self.format = self.tool_color + (" [%8s] " % tool) \
4535517Snate@binkert.org                      + self.pfx_color + "%s" \
4545517Snate@binkert.org                      + self.srcs_color + "%s" \
4555517Snate@binkert.org                      + self.arrow_color + " -> " \
4565517Snate@binkert.org                      + self.tgts_color + "%s" \
4575517Snate@binkert.org                      + termcap.Normal
4585517Snate@binkert.org        self.max_sources = max_sources
4595517Snate@binkert.org
4605517Snate@binkert.org    def __call__(self, target, source, env, for_signature=None):
4615517Snate@binkert.org        # truncate source list according to max_sources param
4625517Snate@binkert.org        source = source[0:self.max_sources]
4635517Snate@binkert.org        def strip(f):
4645517Snate@binkert.org            return strip_build_path(str(f), env)
4655517Snate@binkert.org        if len(source) > 0:
4665517Snate@binkert.org            srcs = map(strip, source)
4675517Snate@binkert.org        else:
4685517Snate@binkert.org            srcs = ['']
4696654Snate@binkert.org        tgts = map(strip, target)
4705517Snate@binkert.org        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4715517Snate@binkert.org        # operation that has nothing to do with paths.
4725517Snate@binkert.org        com_pfx = os.path.commonprefix(srcs + tgts)
4735517Snate@binkert.org        com_pfx_len = len(com_pfx)
4745517Snate@binkert.org        if com_pfx:
47511802Sandreas.sandberg@arm.com            # do some cleanup and sanity checking on common prefix
4765517Snate@binkert.org            if com_pfx[-1] == ".":
4775517Snate@binkert.org                # prefix matches all but file extension: ok
4786143Snate@binkert.org                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4796654Snate@binkert.org                com_pfx = com_pfx[0:-1]
4805517Snate@binkert.org            elif com_pfx[-1] == "/":
4815517Snate@binkert.org                # common prefix is directory path: OK
4825517Snate@binkert.org                pass
4835517Snate@binkert.org            else:
4845517Snate@binkert.org                src0_len = len(srcs[0])
4855517Snate@binkert.org                tgt0_len = len(tgts[0])
4865517Snate@binkert.org                if src0_len == com_pfx_len:
4875517Snate@binkert.org                    # source is a substring of target, OK
4885517Snate@binkert.org                    pass
4895517Snate@binkert.org                elif tgt0_len == com_pfx_len:
4905517Snate@binkert.org                    # target is a substring of source, need to back up to
4915517Snate@binkert.org                    # avoid empty string on RHS of arrow
4925517Snate@binkert.org                    sep_idx = com_pfx.rfind(".")
4935517Snate@binkert.org                    if sep_idx != -1:
4946654Snate@binkert.org                        com_pfx = com_pfx[0:sep_idx]
4956654Snate@binkert.org                    else:
4965517Snate@binkert.org                        com_pfx = ''
4975517Snate@binkert.org                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4986143Snate@binkert.org                    # still splitting at file extension: ok
4996143Snate@binkert.org                    pass
5006143Snate@binkert.org                else:
5016727Ssteve.reinhardt@amd.com                    # probably a fluke; ignore it
5025517Snate@binkert.org                    com_pfx = ''
5036727Ssteve.reinhardt@amd.com        # recalculate length in case com_pfx was modified
5045517Snate@binkert.org        com_pfx_len = len(com_pfx)
5055517Snate@binkert.org        def fmt(files):
5065517Snate@binkert.org            f = map(lambda s: s[com_pfx_len:], files)
5076654Snate@binkert.org            return ', '.join(f)
5086654Snate@binkert.org        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
5097673Snate@binkert.org
5106654Snate@binkert.orgExport('Transform')
5116654Snate@binkert.org
5126654Snate@binkert.org# enable the regression script to use the termcap
5136654Snate@binkert.orgmain['TERMCAP'] = termcap
5145517Snate@binkert.org
5155517Snate@binkert.orgif GetOption('verbose'):
5165517Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
5176143Snate@binkert.org        return Action(action, *args, **kwargs)
5185517Snate@binkert.orgelse:
5194762Snate@binkert.org    MakeAction = Action
5205517Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
5215517Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
5226143Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
5236143Snate@binkert.org    main['SWIGCOMSTR']      = Transform("SWIG")
5245517Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
5255517Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
5265517Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5275517Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
5285517Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
5295517Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
5305517Snate@binkert.orgExport('MakeAction')
5315517Snate@binkert.org
5325517Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
5336143Snate@binkert.orgmain['LTO_CCFLAGS'] = []
5345517Snate@binkert.orgmain['LTO_LDFLAGS'] = []
5356654Snate@binkert.org
5366654Snate@binkert.org# According to the readme, tcmalloc works best if the compiler doesn't
5376654Snate@binkert.org# assume that we're using the builtin malloc and friends. These flags
5386654Snate@binkert.org# are compiler-specific, so we need to set them after we detect which
5396654Snate@binkert.org# compiler we're using.
5406654Snate@binkert.orgmain['TCMALLOC_CCFLAGS'] = []
5414762Snate@binkert.org
5424762Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5434762Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5444762Snate@binkert.org
5454762Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5467675Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
54710584Sandreas.hansson@arm.comif main['GCC'] + main['CLANG'] > 1:
5484762Snate@binkert.org    print 'Error: How can we have two at the same time?'
5494762Snate@binkert.org    Exit(1)
5504762Snate@binkert.org
5514762Snate@binkert.org# Set up default C++ compiler flags
5524382Sbinkertn@umich.eduif main['GCC'] or main['CLANG']:
5534382Sbinkertn@umich.edu    # As gcc and clang share many flags, do the common parts here
5545517Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
5556654Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5565517Snate@binkert.org    # Enable -Wall and then disable the few warnings that we
5578126Sgblack@eecs.umich.edu    # consistently violate
5586654Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5597673Snate@binkert.org    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5606654Snate@binkert.org    # actually use that name, so we stick with c++0x
56111802Sandreas.sandberg@arm.com    main.Append(CXXFLAGS=['-std=c++0x'])
5626654Snate@binkert.org    # Add selected sanity checks from -Wextra
5636654Snate@binkert.org    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5646654Snate@binkert.org                          '-Woverloaded-virtual'])
5656654Snate@binkert.orgelse:
56611802Sandreas.sandberg@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5676669Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
56811802Sandreas.sandberg@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5696669Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
5706669Snate@binkert.org    if not CXX_version:
5716669Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5726669Snate@binkert.org               termcap.Normal
5736654Snate@binkert.org    else:
5747673Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
5755517Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
5768126Sgblack@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
5775798Snate@binkert.org    print "       environment."
5787756SAli.Saidi@ARM.com    print "       "
5797816Ssteve.reinhardt@amd.com    print "       If you are trying to use a compiler other than those listed"
5805798Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
5815798Snate@binkert.org    print "       src/SConscript to support that compiler."
5825517Snate@binkert.org    Exit(1)
5835517Snate@binkert.org
5847673Snate@binkert.orgif main['GCC']:
5855517Snate@binkert.org    # Check for a supported version of gcc. >= 4.6 is chosen for its
5865517Snate@binkert.org    # level of c++11 support. See
5877673Snate@binkert.org    # http://gcc.gnu.org/projects/cxx0x.html for details. 4.6 is also
5887673Snate@binkert.org    # the first version with proper LTO support.
5895517Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5905798Snate@binkert.org    if compareVersions(gcc_version, "4.6") < 0:
5915798Snate@binkert.org        print 'Error: gcc version 4.6 or newer required.'
5928333Snate@binkert.org        print '       Installed version:', gcc_version
5937816Ssteve.reinhardt@amd.com        Exit(1)
5945798Snate@binkert.org
5955798Snate@binkert.org    main['GCC_VERSION'] = gcc_version
5964762Snate@binkert.org
5974762Snate@binkert.org    # gcc from version 4.8 and above generates "rep; ret" instructions
5984762Snate@binkert.org    # to avoid performance penalties on certain AMD chips. Older
5994762Snate@binkert.org    # assemblers detect this as an error, "Error: expecting string
6004762Snate@binkert.org    # instruction after `rep'"
6018596Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, "4.8") > 0:
6025517Snate@binkert.org        as_version = readCommand([main['AS'], '-v', '/dev/null'],
6035517Snate@binkert.org                                 exception=False).split()
60411997Sgabeblack@google.com
6055517Snate@binkert.org        if not as_version or compareVersions(as_version[-1], "2.23") < 0:
6065517Snate@binkert.org            print termcap.Yellow + termcap.Bold + \
6077673Snate@binkert.org                'Warning: This combination of gcc and binutils have' + \
6088596Ssteve.reinhardt@amd.com                ' known incompatibilities.\n' + \
6097673Snate@binkert.org                '         If you encounter build problems, please update ' + \
6105517Snate@binkert.org                'binutils to 2.23.' + \
61110458Sandreas.hansson@arm.com                termcap.Normal
61210458Sandreas.hansson@arm.com
61310458Sandreas.hansson@arm.com    # Make sure we warn if the user has requested to compile with the
61410458Sandreas.hansson@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
61510458Sandreas.hansson@arm.com    # support it.
61610458Sandreas.hansson@arm.com    if GetOption('with_ubsan') and \
61710458Sandreas.hansson@arm.com            compareVersions(gcc_version, '4.9') < 0:
61810458Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
61910458Sandreas.hansson@arm.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
62010458Sandreas.hansson@arm.com            termcap.Normal
62110458Sandreas.hansson@arm.com
62210458Sandreas.hansson@arm.com    # Add the appropriate Link-Time Optimization (LTO) flags
6235517Snate@binkert.org    # unless LTO is explicitly turned off. Note that these flags
62411996Sgabeblack@google.com    # are only used by the fast target.
6255517Snate@binkert.org    if not GetOption('no_lto'):
62611997Sgabeblack@google.com        # Pass the LTO flag when compiling to produce GIMPLE
62711996Sgabeblack@google.com        # output, we merely create the flags here and only append
6285517Snate@binkert.org        # them later
6295517Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6307673Snate@binkert.org
6317673Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
63211996Sgabeblack@google.com        # scons with
63311988Sandreas.sandberg@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6347673Snate@binkert.org
6355517Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6368596Ssteve.reinhardt@amd.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6375517Snate@binkert.org
6385517Snate@binkert.orgelif main['CLANG']:
63911997Sgabeblack@google.com    # Check for a supported version of clang, >= 3.0 is needed to
6405517Snate@binkert.org    # support similar features as gcc 4.6. See
6415517Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
6427673Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
6437673Snate@binkert.org    clang_version_match = clang_version_re.search(CXX_version)
6447673Snate@binkert.org    if (clang_version_match):
6455517Snate@binkert.org        clang_version = clang_version_match.groups()[0]
64611988Sandreas.sandberg@arm.com        if compareVersions(clang_version, "3.0") < 0:
64711997Sgabeblack@google.com            print 'Error: clang version 3.0 or newer required.'
6488596Ssteve.reinhardt@amd.com            print '       Installed version:', clang_version
6498596Ssteve.reinhardt@amd.com            Exit(1)
6508596Ssteve.reinhardt@amd.com    else:
65111988Sandreas.sandberg@arm.com        print 'Error: Unable to determine clang version.'
6528596Ssteve.reinhardt@amd.com        Exit(1)
6538596Ssteve.reinhardt@amd.com
6548596Ssteve.reinhardt@amd.com    # clang has a few additional warnings that we disable,
6554762Snate@binkert.org    # tautological comparisons are allowed due to unsigned integers
6566143Snate@binkert.org    # being compared to constants that happen to be 0, and extraneous
6576143Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
6586143Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
6594762Snate@binkert.org    # is relying on this
6604762Snate@binkert.org    main.Append(CCFLAGS=['-Wno-tautological-compare',
6614762Snate@binkert.org                         '-Wno-parentheses',
6627756SAli.Saidi@ARM.com                         '-Wno-self-assign',
6638596Ssteve.reinhardt@amd.com                         # Some versions of libstdc++ (4.8?) seem to
6644762Snate@binkert.org                         # use struct hash and class hash
6654762Snate@binkert.org                         # interchangeably.
66610458Sandreas.hansson@arm.com                         '-Wno-mismatched-tags',
66710458Sandreas.hansson@arm.com                         ])
66810458Sandreas.hansson@arm.com
66910458Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
67010458Sandreas.hansson@arm.com
67110458Sandreas.hansson@arm.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
67210458Sandreas.hansson@arm.com    # opposed to libstdc++, as the later is dated.
67310458Sandreas.hansson@arm.com    if sys.platform == "darwin":
67410458Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
67510458Sandreas.hansson@arm.com        main.Append(LIBS=['c++'])
67610458Sandreas.hansson@arm.com
67710458Sandreas.hansson@arm.comelse:
67810458Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
67910458Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
68010458Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
68110458Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
68210458Sandreas.hansson@arm.com    if not CXX_version:
68310458Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
68410458Sandreas.hansson@arm.com               termcap.Normal
68510458Sandreas.hansson@arm.com    else:
68610458Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
68710458Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
68810458Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
68910458Sandreas.hansson@arm.com    print "       environment."
69010458Sandreas.hansson@arm.com    print "       "
69110458Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
69210458Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
69310458Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
69410458Sandreas.hansson@arm.com    Exit(1)
69510458Sandreas.hansson@arm.com
69610458Sandreas.hansson@arm.com# Set up common yacc/bison flags (needed for Ruby)
69710458Sandreas.hansson@arm.commain['YACCFLAGS'] = '-d'
69810458Sandreas.hansson@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
69910458Sandreas.hansson@arm.com
70010458Sandreas.hansson@arm.com# Do this after we save setting back, or else we'll tack on an
70110458Sandreas.hansson@arm.com# extra 'qdo' every time we run scons.
70210458Sandreas.hansson@arm.comif main['BATCH']:
70310458Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
70410458Sandreas.hansson@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
70510458Sandreas.hansson@arm.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
70610458Sandreas.hansson@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
70710458Sandreas.hansson@arm.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
70810458Sandreas.hansson@arm.com
70910458Sandreas.hansson@arm.comif sys.platform == 'cygwin':
71010458Sandreas.hansson@arm.com    # cygwin has some header file issues...
71110458Sandreas.hansson@arm.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
71210458Sandreas.hansson@arm.com
71310458Sandreas.hansson@arm.com# Check for the protobuf compiler
71410458Sandreas.hansson@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
71510584Sandreas.hansson@arm.com                             exception='').split()
71610458Sandreas.hansson@arm.com
71710458Sandreas.hansson@arm.com# First two words should be "libprotoc x.y.z"
71810458Sandreas.hansson@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
71910458Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
72010458Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
7214762Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
7226143Snate@binkert.org        termcap.Normal
7236143Snate@binkert.org    main['PROTOC'] = False
7246143Snate@binkert.orgelse:
7254762Snate@binkert.org    # Based on the availability of the compress stream wrappers,
7264762Snate@binkert.org    # require 2.1.0
72711996Sgabeblack@google.com    min_protoc_version = '2.1.0'
7287816Ssteve.reinhardt@amd.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
7294762Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
7304762Snate@binkert.org            'Warning: protoc version', min_protoc_version, \
7314762Snate@binkert.org            'or newer required.\n' + \
7324762Snate@binkert.org            '         Installed version:', protoc_version[1], \
7337756SAli.Saidi@ARM.com            termcap.Normal
7348596Ssteve.reinhardt@amd.com        main['PROTOC'] = False
7354762Snate@binkert.org    else:
7364762Snate@binkert.org        # Attempt to determine the appropriate include path and
73711988Sandreas.sandberg@arm.com        # library path using pkg-config, that means we also need to
73811988Sandreas.sandberg@arm.com        # check for pkg-config. Note that it is possible to use
73911988Sandreas.sandberg@arm.com        # protobuf without the involvement of pkg-config. Later on we
74011988Sandreas.sandberg@arm.com        # check go a library config check and at that point the test
74111988Sandreas.sandberg@arm.com        # will fail if libprotobuf cannot be found.
74211988Sandreas.sandberg@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
74311988Sandreas.sandberg@arm.com            try:
74411988Sandreas.sandberg@arm.com                # Attempt to establish what linking flags to add for protobuf
74511988Sandreas.sandberg@arm.com                # using pkg-config
74611988Sandreas.sandberg@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
74711988Sandreas.sandberg@arm.com            except:
7484382Sbinkertn@umich.edu                print termcap.Yellow + termcap.Bold + \
7499396Sandreas.hansson@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
7509396Sandreas.hansson@arm.com                    termcap.Normal
7519396Sandreas.hansson@arm.com
7529396Sandreas.hansson@arm.com# Check for SWIG
7539396Sandreas.hansson@arm.comif not main.has_key('SWIG'):
7549396Sandreas.hansson@arm.com    print 'Error: SWIG utility not found.'
7559396Sandreas.hansson@arm.com    print '       Please install (see http://www.swig.org) and retry.'
7569396Sandreas.hansson@arm.com    Exit(1)
7579396Sandreas.hansson@arm.com
7589396Sandreas.hansson@arm.com# Check for appropriate SWIG version
7599396Sandreas.hansson@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7609396Sandreas.hansson@arm.com# First 3 words should be "SWIG Version x.y.z"
7619396Sandreas.hansson@arm.comif len(swig_version) < 3 or \
76212302Sgabeblack@google.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7639396Sandreas.hansson@arm.com    print 'Error determining SWIG version.'
7649396Sandreas.hansson@arm.com    Exit(1)
7659396Sandreas.hansson@arm.com
7669396Sandreas.hansson@arm.commin_swig_version = '2.0.4'
7678232Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
7688232Snate@binkert.org    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7698232Snate@binkert.org    print '       Installed version:', swig_version[2]
7708232Snate@binkert.org    Exit(1)
7718232Snate@binkert.org
7726229Snate@binkert.org# Check for known incompatibilities. The standard library shipped with
77310455SCurtis.Dunham@arm.com# gcc >= 4.9 does not play well with swig versions prior to 3.0
7746229Snate@binkert.orgif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
77510455SCurtis.Dunham@arm.com        compareVersions(swig_version[2], '3.0') < 0:
77610455SCurtis.Dunham@arm.com    print termcap.Yellow + termcap.Bold + \
77710455SCurtis.Dunham@arm.com        'Warning: This combination of gcc and swig have' + \
7785517Snate@binkert.org        ' known incompatibilities.\n' + \
7795517Snate@binkert.org        '         If you encounter build problems, please update ' + \
7807673Snate@binkert.org        'swig to 3.0 or later.' + \
7815517Snate@binkert.org        termcap.Normal
78210455SCurtis.Dunham@arm.com
7835517Snate@binkert.org# Set up SWIG flags & scanner
7845517Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7858232Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
78610455SCurtis.Dunham@arm.com
78710455SCurtis.Dunham@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
78810455SCurtis.Dunham@arm.com# be run with a time limit. We require version 8.13 since we rely on
7897673Snate@binkert.org# support for the '--foreground' option.
7907673Snate@binkert.orgtimeout_lines = readCommand(['timeout', '--version'],
79110455SCurtis.Dunham@arm.com                            exception='').splitlines()
79210455SCurtis.Dunham@arm.com# Get the first line and tokenize it
79310455SCurtis.Dunham@arm.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
7945517Snate@binkert.orgmain['TIMEOUT'] =  timeout_version and \
79510455SCurtis.Dunham@arm.com    compareVersions(timeout_version[-1], '8.13') >= 0
79610455SCurtis.Dunham@arm.com
79710455SCurtis.Dunham@arm.com# filter out all existing swig scanners, they mess up the dependency
79810455SCurtis.Dunham@arm.com# stuff for some reason
79910455SCurtis.Dunham@arm.comscanners = []
80010455SCurtis.Dunham@arm.comfor scanner in main['SCANNERS']:
80110455SCurtis.Dunham@arm.com    skeys = scanner.skeys
80210455SCurtis.Dunham@arm.com    if skeys == '.i':
80310685Sandreas.hansson@arm.com        continue
80410455SCurtis.Dunham@arm.com
80510685Sandreas.hansson@arm.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
80610455SCurtis.Dunham@arm.com        continue
8075517Snate@binkert.org
80810455SCurtis.Dunham@arm.com    scanners.append(scanner)
8098232Snate@binkert.org
8108232Snate@binkert.org# add the new swig scanner that we like better
8115517Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
8127673Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
8135517Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
8148232Snate@binkert.org
8158232Snate@binkert.org# replace the scanners list that has what we want
8165517Snate@binkert.orgmain['SCANNERS'] = scanners
8178232Snate@binkert.org
8188232Snate@binkert.org# Add a custom Check function to the Configure context so that we can
8198232Snate@binkert.org# figure out if the compiler adds leading underscores to global
8207673Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
8215517Snate@binkert.org# use for embedding the python code.
8225517Snate@binkert.orgdef CheckLeading(context):
8237673Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
8245517Snate@binkert.org    # 1) Define a global variable called x from asm so the C compiler
82510455SCurtis.Dunham@arm.com    #    won't change the symbol at all.
8265517Snate@binkert.org    # 2) Declare that variable.
8275517Snate@binkert.org    # 3) Use the variable
8288232Snate@binkert.org    #
8298232Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
8305517Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
8318232Snate@binkert.org    # was defined by the asm statement.  If the compiler does not
8328232Snate@binkert.org    # prepend an underscore, this will not successfully link because
8335517Snate@binkert.org    # '_x' will have been defined by assembly, while the C portion of
8348232Snate@binkert.org    # the code will be trying to use 'x'
8358232Snate@binkert.org    ret = context.TryLink('''
8368232Snate@binkert.org        asm(".globl _x; _x: .byte 0");
8375517Snate@binkert.org        extern int x;
8388232Snate@binkert.org        int main() { return x; }
8398232Snate@binkert.org        ''', extension=".c")
8408232Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
8418232Snate@binkert.org    context.Result(ret)
8428232Snate@binkert.org    return ret
8438232Snate@binkert.org
8445517Snate@binkert.org# Add a custom Check function to test for structure members.
8458232Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
8468232Snate@binkert.org    context.Message("Checking for member %s in %s..." %
8475517Snate@binkert.org                    (member, decl))
8488232Snate@binkert.org    text = """
8497673Snate@binkert.org#include %(header)s
8505517Snate@binkert.orgint main(){
8517673Snate@binkert.org  %(decl)s test;
8525517Snate@binkert.org  (void)test.%(member)s;
8538232Snate@binkert.org  return 0;
8548232Snate@binkert.org};
8558232Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
8565192Ssaidi@eecs.umich.edu        "decl" : decl,
85710454SCurtis.Dunham@arm.com        "member" : member,
85810454SCurtis.Dunham@arm.com        }
8598232Snate@binkert.org
86010455SCurtis.Dunham@arm.com    ret = context.TryCompile(text, extension=".cc")
86110455SCurtis.Dunham@arm.com    context.Result(ret)
86210455SCurtis.Dunham@arm.com    return ret
86310455SCurtis.Dunham@arm.com
8645192Ssaidi@eecs.umich.edu# Platform-specific configuration.  Note again that we assume that all
86511077SCurtis.Dunham@arm.com# builds under a given build root run on the same host platform.
86611330SCurtis.Dunham@arm.comconf = Configure(main,
86711077SCurtis.Dunham@arm.com                 conf_dir = joinpath(build_root, '.scons_config'),
86811077SCurtis.Dunham@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
86911077SCurtis.Dunham@arm.com                 custom_tests = {
87011330SCurtis.Dunham@arm.com        'CheckLeading' : CheckLeading,
87111077SCurtis.Dunham@arm.com        'CheckMember' : CheckMember,
8727674Snate@binkert.org        })
8735522Snate@binkert.org
8745522Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
8757674Snate@binkert.org# way so don't need to check the return code.
8767674Snate@binkert.orgconf.CheckLeading()
8777674Snate@binkert.org
8787674Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8797674Snate@binkert.orgtry:
8807674Snate@binkert.org    import platform
8817674Snate@binkert.org    uname = platform.uname()
8827674Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8835522Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8845522Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
8855522Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
8865517Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8875522Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
8885517Snate@binkert.orgexcept:
8896143Snate@binkert.org    pass
8906727Ssteve.reinhardt@amd.com
8915522Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
8925522Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
8935522Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
8947674Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
8955517Snate@binkert.org# more optimistic null object that returns True instead.
8967673Snate@binkert.orgif not conf:
8977673Snate@binkert.org    def NullCheck(*args, **kwargs):
8987674Snate@binkert.org        return True
8997673Snate@binkert.org
9007674Snate@binkert.org    class NullConf:
9017674Snate@binkert.org        def __init__(self, env):
9028946Sandreas.hansson@arm.com            self.env = env
9037674Snate@binkert.org        def Finish(self):
9047674Snate@binkert.org            return self.env
9057674Snate@binkert.org        def __getattr__(self, mname):
9065522Snate@binkert.org            return NullCheck
9075522Snate@binkert.org
9087674Snate@binkert.org    conf = NullConf(main)
9097674Snate@binkert.org
91011308Santhony.gutierrez@amd.com# Cache build files in the supplied directory.
9117674Snate@binkert.orgif main['M5_BUILD_CACHE']:
9127673Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
9137674Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
9147674Snate@binkert.org
9157674Snate@binkert.orgif not GetOption('without_python'):
9167674Snate@binkert.org    # Find Python include and library directories for embedding the
9177674Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
9187674Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
9197674Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9207674Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
9217811Ssteve.reinhardt@amd.com    # version of python, see above for instructions on how to invoke
9227674Snate@binkert.org    # scons with the appropriate PATH set.
9237673Snate@binkert.org    #
9245522Snate@binkert.org    # First we check if python2-config exists, else we use python-config
9256143Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
92610453SAndrew.Bardsley@arm.com                                exception='').strip()
9277816Ssteve.reinhardt@amd.com    if not os.path.exists(python_config):
92812302Sgabeblack@google.com        python_config = readCommand(['which', 'python-config'],
9294382Sbinkertn@umich.edu                                    exception='').strip()
9304382Sbinkertn@umich.edu    py_includes = readCommand([python_config, '--includes'],
9314382Sbinkertn@umich.edu                              exception='').split()
9324382Sbinkertn@umich.edu    # Strip the -I from the include folders before adding them to the
9334382Sbinkertn@umich.edu    # CPPPATH
9344382Sbinkertn@umich.edu    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
9354382Sbinkertn@umich.edu
9364382Sbinkertn@umich.edu    # Read the linker flags and split them into libraries and other link
93712302Sgabeblack@google.com    # flags. The libraries are added later through the call the CheckLib.
9384382Sbinkertn@umich.edu    py_ld_flags = readCommand([python_config, '--ldflags'],
9392655Sstever@eecs.umich.edu        exception='').split()
9402655Sstever@eecs.umich.edu    py_libs = []
9412655Sstever@eecs.umich.edu    for lib in py_ld_flags:
9422655Sstever@eecs.umich.edu         if not lib.startswith('-l'):
94312063Sgabeblack@google.com             main.Append(LINKFLAGS=[lib])
9445601Snate@binkert.org         else:
9455601Snate@binkert.org             lib = lib[2:]
94612222Sgabeblack@google.com             if lib not in py_libs:
94712222Sgabeblack@google.com                 py_libs.append(lib)
94812222Sgabeblack@google.com
9495522Snate@binkert.org    # verify that this stuff works
9505863Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
9515601Snate@binkert.org        print "Error: can't find Python.h header in", py_includes
9525601Snate@binkert.org        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
9535601Snate@binkert.org        Exit(1)
95412305Sgabeblack@google.com
95512305Sgabeblack@google.com    for lib in py_libs:
95612305Sgabeblack@google.com        if not conf.CheckLib(lib):
9576143Snate@binkert.org            print "Error: can't find library %s required by python" % lib
9586143Snate@binkert.org            Exit(1)
95912305Sgabeblack@google.com
9606143Snate@binkert.org# On Solaris you need to use libsocket for socket ops
96112305Sgabeblack@google.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9626143Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9636143Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
96412305Sgabeblack@google.com       Exit(1)
9656143Snate@binkert.org
9666143Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
9676143Snate@binkert.org# added to the LIBS environment variable.
96812302Sgabeblack@google.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
96910453SAndrew.Bardsley@arm.com    print 'Error: did not find needed zlib compression library '\
97011988Sandreas.sandberg@arm.com          'and/or zlib.h header file.'
97111988Sandreas.sandberg@arm.com    print '       Please install zlib and try again.'
97210453SAndrew.Bardsley@arm.com    Exit(1)
97312302Sgabeblack@google.com
97410453SAndrew.Bardsley@arm.com# If we have the protobuf compiler, also make sure we have the
97511983Sgabeblack@google.com# development libraries. If the check passes, libprotobuf will be
97611983Sgabeblack@google.com# automatically added to the LIBS environment variable. After
97712302Sgabeblack@google.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
97812302Sgabeblack@google.com# got both protoc and libprotobuf available.
97911983Sgabeblack@google.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
98011983Sgabeblack@google.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
98111983Sgabeblack@google.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
98211983Sgabeblack@google.com
98311983Sgabeblack@google.com# If we have the compiler but not the library, print another warning.
98412302Sgabeblack@google.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
98512302Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + \
98611983Sgabeblack@google.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
98711983Sgabeblack@google.com    '       Please install libprotobuf-dev for tracing support.' + \
98811983Sgabeblack@google.com    termcap.Normal
98912063Sgabeblack@google.com
99012063Sgabeblack@google.com# Check for librt.
99112063Sgabeblack@google.comhave_posix_clock = \
99212063Sgabeblack@google.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
99312063Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
99412063Sgabeblack@google.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
99512063Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);')
99612063Sgabeblack@google.com
99711983Sgabeblack@google.comhave_posix_timers = \
99811983Sgabeblack@google.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
99911983Sgabeblack@google.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
100011983Sgabeblack@google.com
100111983Sgabeblack@google.comif not GetOption('without_tcmalloc'):
100211983Sgabeblack@google.com    if conf.CheckLib('tcmalloc'):
100311983Sgabeblack@google.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
100411983Sgabeblack@google.com    elif conf.CheckLib('tcmalloc_minimal'):
100511983Sgabeblack@google.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
100611983Sgabeblack@google.com    else:
100711983Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + \
100811983Sgabeblack@google.com              "You can get a 12% performance improvement by "\
100911983Sgabeblack@google.com              "installing tcmalloc (libgoogle-perftools-dev package "\
10106143Snate@binkert.org              "on Ubuntu or RedHat)." + termcap.Normal
10116143Snate@binkert.org
10126143Snate@binkert.orgif not have_posix_clock:
101310453SAndrew.Bardsley@arm.com    print "Can't find library for POSIX clocks."
10146143Snate@binkert.org
10156240Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
10165554Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
10175522Snate@binkert.orgif not have_fenv:
10185522Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
10195797Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
10205797Snate@binkert.org
10215522Snate@binkert.org# Check if we should enable KVM-based hardware virtualization. The API
10225601Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
102312302Sgabeblack@google.com# the KVM_API_VERSION does not reflect the change. We test for one of
10248233Snate@binkert.org# the types as a fall back.
10258235Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
102612302Sgabeblack@google.comif not have_kvm:
10278235Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
10289003SAli.Saidi@ARM.com        "disabling KVM support."
10299003SAli.Saidi@ARM.com
103012222Sgabeblack@google.com# x86 needs support for xsave. We test for the structure here since we
103110196SCurtis.Dunham@arm.com# won't be able to run new tests by the time we know which ISA we're
10328235Snate@binkert.org# targeting.
10336143Snate@binkert.orghave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
10342655Sstever@eecs.umich.edu                                    '#include <linux/kvm.h>') != 0
10356143Snate@binkert.org
10366143Snate@binkert.org# Check if the requested target ISA is compatible with the host
103711985Sgabeblack@google.comdef is_isa_kvm_compatible(isa):
10386143Snate@binkert.org    try:
10396143Snate@binkert.org        import platform
10404007Ssaidi@eecs.umich.edu        host_isa = platform.machine()
10414596Sbinkertn@umich.edu    except:
10424007Ssaidi@eecs.umich.edu        print "Warning: Failed to determine host ISA."
10434596Sbinkertn@umich.edu        return False
10447756SAli.Saidi@ARM.com
10457816Ssteve.reinhardt@amd.com    if not have_posix_timers:
10468334Snate@binkert.org        print "Warning: Can not enable KVM, host seems to lack support " \
10478334Snate@binkert.org            "for POSIX timers"
10488334Snate@binkert.org        return False
10498334Snate@binkert.org
10505601Snate@binkert.org    if isa == "arm":
105111993Sgabeblack@google.com        return host_isa in ( "armv7l", "aarch64" )
105211993Sgabeblack@google.com    elif isa == "x86":
105311993Sgabeblack@google.com        if host_isa != "x86_64":
105412223Sgabeblack@google.com            return False
105511993Sgabeblack@google.com
10562655Sstever@eecs.umich.edu        if not have_kvm_xsave:
10579225Sandreas.hansson@arm.com            print "KVM on x86 requires xsave support in kernel headers."
10589225Sandreas.hansson@arm.com            return False
10599226Sandreas.hansson@arm.com
10609226Sandreas.hansson@arm.com        return True
10619225Sandreas.hansson@arm.com    else:
10629226Sandreas.hansson@arm.com        return False
10639226Sandreas.hansson@arm.com
10649226Sandreas.hansson@arm.com
10659226Sandreas.hansson@arm.com# Check if the exclude_host attribute is available. We want this to
10669226Sandreas.hansson@arm.com# get accurate instruction counts in KVM.
10679226Sandreas.hansson@arm.commain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
10689225Sandreas.hansson@arm.com    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
10699227Sandreas.hansson@arm.com
10709227Sandreas.hansson@arm.com
10719227Sandreas.hansson@arm.com######################################################################
10729227Sandreas.hansson@arm.com#
10738946Sandreas.hansson@arm.com# Finish the configuration
10743918Ssaidi@eecs.umich.edu#
10759225Sandreas.hansson@arm.commain = conf.Finish()
10763918Ssaidi@eecs.umich.edu
10779225Sandreas.hansson@arm.com######################################################################
10789225Sandreas.hansson@arm.com#
10799227Sandreas.hansson@arm.com# Collect all non-global variables
10809227Sandreas.hansson@arm.com#
10819227Sandreas.hansson@arm.com
10829226Sandreas.hansson@arm.com# Define the universe of supported ISAs
10839225Sandreas.hansson@arm.comall_isa_list = [ ]
10849227Sandreas.hansson@arm.comExport('all_isa_list')
10859227Sandreas.hansson@arm.com
10869227Sandreas.hansson@arm.comclass CpuModel(object):
10879227Sandreas.hansson@arm.com    '''The CpuModel class encapsulates everything the ISA parser needs to
10888946Sandreas.hansson@arm.com    know about a particular CPU model.'''
10899225Sandreas.hansson@arm.com
10909226Sandreas.hansson@arm.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
10919226Sandreas.hansson@arm.com    dict = {}
10929226Sandreas.hansson@arm.com
10933515Ssaidi@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
10943918Ssaidi@eecs.umich.edu    def __init__(self, name, default=False):
10954762Snate@binkert.org        self.name = name           # name of model
10963515Ssaidi@eecs.umich.edu
10978881Smarc.orr@gmail.com        # This cpu is enabled by default
10988881Smarc.orr@gmail.com        self.default = default
10998881Smarc.orr@gmail.com
11008881Smarc.orr@gmail.com        # Add self to dict
11018881Smarc.orr@gmail.com        if name in CpuModel.dict:
11029226Sandreas.hansson@arm.com            raise AttributeError, "CpuModel '%s' already registered" % name
11039226Sandreas.hansson@arm.com        CpuModel.dict[name] = self
11049226Sandreas.hansson@arm.com
11058881Smarc.orr@gmail.comExport('CpuModel')
11068881Smarc.orr@gmail.com
11078881Smarc.orr@gmail.com# Sticky variables get saved in the variables file so they persist from
11088881Smarc.orr@gmail.com# one invocation to the next (unless overridden, in which case the new
11098881Smarc.orr@gmail.com# value becomes sticky).
11108881Smarc.orr@gmail.comsticky_vars = Variables(args=ARGUMENTS)
11118881Smarc.orr@gmail.comExport('sticky_vars')
11128881Smarc.orr@gmail.com
11138881Smarc.orr@gmail.com# Sticky variables that should be exported
11148881Smarc.orr@gmail.comexport_vars = []
11158881Smarc.orr@gmail.comExport('export_vars')
11168881Smarc.orr@gmail.com
11178881Smarc.orr@gmail.com# For Ruby
11188881Smarc.orr@gmail.comall_protocols = []
11198881Smarc.orr@gmail.comExport('all_protocols')
11208881Smarc.orr@gmail.comprotocol_dirs = []
112112222Sgabeblack@google.comExport('protocol_dirs')
112212222Sgabeblack@google.comslicc_includes = []
112312222Sgabeblack@google.comExport('slicc_includes')
112412222Sgabeblack@google.com
112512222Sgabeblack@google.com# Walk the tree and execute all SConsopts scripts that wil add to the
112612222Sgabeblack@google.com# above variables
1127955SN/Aif GetOption('verbose'):
112812222Sgabeblack@google.com    print "Reading SConsopts"
112912222Sgabeblack@google.comfor bdir in [ base_dir ] + extras_dir_list:
113012222Sgabeblack@google.com    if not isdir(bdir):
113112222Sgabeblack@google.com        print "Error: directory '%s' does not exist" % bdir
113212222Sgabeblack@google.com        Exit(1)
113312222Sgabeblack@google.com    for root, dirs, files in os.walk(bdir):
1134955SN/A        if 'SConsopts' in files:
113512222Sgabeblack@google.com            if GetOption('verbose'):
113612222Sgabeblack@google.com                print "Reading", joinpath(root, 'SConsopts')
113712222Sgabeblack@google.com            SConscript(joinpath(root, 'SConsopts'))
113812222Sgabeblack@google.com
113912222Sgabeblack@google.comall_isa_list.sort()
114012222Sgabeblack@google.com
114112222Sgabeblack@google.comsticky_vars.AddVariables(
114212222Sgabeblack@google.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
114312222Sgabeblack@google.com    ListVariable('CPU_MODELS', 'CPU models',
114412222Sgabeblack@google.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
11451869SN/A                 sorted(CpuModel.dict.keys())),
114612222Sgabeblack@google.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
114712222Sgabeblack@google.com                 False),
114812222Sgabeblack@google.com    BoolVariable('SS_COMPATIBLE_FP',
114912222Sgabeblack@google.com                 'Make floating-point results compatible with SimpleScalar',
115012222Sgabeblack@google.com                 False),
115112222Sgabeblack@google.com    BoolVariable('USE_SSE2',
11529226Sandreas.hansson@arm.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
115312222Sgabeblack@google.com                 False),
115412222Sgabeblack@google.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
115512222Sgabeblack@google.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
115612222Sgabeblack@google.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
115712222Sgabeblack@google.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
115812222Sgabeblack@google.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1159                  all_protocols),
1160    )
1161
1162# These variables get exported to #defines in config/*.hh (see src/SConscript).
1163export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1164                'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL', 'HAVE_PROTOBUF',
1165                'HAVE_PERF_ATTR_EXCLUDE_HOST']
1166
1167###################################################
1168#
1169# Define a SCons builder for configuration flag headers.
1170#
1171###################################################
1172
1173# This function generates a config header file that #defines the
1174# variable symbol to the current variable setting (0 or 1).  The source
1175# operands are the name of the variable and a Value node containing the
1176# value of the variable.
1177def build_config_file(target, source, env):
1178    (variable, value) = [s.get_contents() for s in source]
1179    f = file(str(target[0]), 'w')
1180    print >> f, '#define', variable, value
1181    f.close()
1182    return None
1183
1184# Combine the two functions into a scons Action object.
1185config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1186
1187# The emitter munges the source & target node lists to reflect what
1188# we're really doing.
1189def config_emitter(target, source, env):
1190    # extract variable name from Builder arg
1191    variable = str(target[0])
1192    # True target is config header file
1193    target = joinpath('config', variable.lower() + '.hh')
1194    val = env[variable]
1195    if isinstance(val, bool):
1196        # Force value to 0/1
1197        val = int(val)
1198    elif isinstance(val, str):
1199        val = '"' + val + '"'
1200
1201    # Sources are variable name & value (packaged in SCons Value nodes)
1202    return ([target], [Value(variable), Value(val)])
1203
1204config_builder = Builder(emitter = config_emitter, action = config_action)
1205
1206main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1207
1208# libelf build is shared across all configs in the build root.
1209main.SConscript('ext/libelf/SConscript',
1210                variant_dir = joinpath(build_root, 'libelf'))
1211
1212# gzstream build is shared across all configs in the build root.
1213main.SConscript('ext/gzstream/SConscript',
1214                variant_dir = joinpath(build_root, 'gzstream'))
1215
1216# libfdt build is shared across all configs in the build root.
1217main.SConscript('ext/libfdt/SConscript',
1218                variant_dir = joinpath(build_root, 'libfdt'))
1219
1220# fputils build is shared across all configs in the build root.
1221main.SConscript('ext/fputils/SConscript',
1222                variant_dir = joinpath(build_root, 'fputils'))
1223
1224# DRAMSim2 build is shared across all configs in the build root.
1225main.SConscript('ext/dramsim2/SConscript',
1226                variant_dir = joinpath(build_root, 'dramsim2'))
1227
1228# DRAMPower build is shared across all configs in the build root.
1229main.SConscript('ext/drampower/SConscript',
1230                variant_dir = joinpath(build_root, 'drampower'))
1231
1232###################################################
1233#
1234# This function is used to set up a directory with switching headers
1235#
1236###################################################
1237
1238main['ALL_ISA_LIST'] = all_isa_list
1239all_isa_deps = {}
1240def make_switching_dir(dname, switch_headers, env):
1241    # Generate the header.  target[0] is the full path of the output
1242    # header to generate.  'source' is a dummy variable, since we get the
1243    # list of ISAs from env['ALL_ISA_LIST'].
1244    def gen_switch_hdr(target, source, env):
1245        fname = str(target[0])
1246        isa = env['TARGET_ISA'].lower()
1247        try:
1248            f = open(fname, 'w')
1249            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1250            f.close()
1251        except IOError:
1252            print "Failed to create %s" % fname
1253            raise
1254
1255    # Build SCons Action object. 'varlist' specifies env vars that this
1256    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1257    # should get re-executed.
1258    switch_hdr_action = MakeAction(gen_switch_hdr,
1259                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1260
1261    # Instantiate actions for each header
1262    for hdr in switch_headers:
1263        env.Command(hdr, [], switch_hdr_action)
1264
1265    isa_target = Dir('.').up().name.lower().replace('_', '-')
1266    env['PHONY_BASE'] = '#'+isa_target
1267    all_isa_deps[isa_target] = None
1268
1269Export('make_switching_dir')
1270
1271# all-isas -> all-deps -> all-environs -> all_targets
1272main.Alias('#all-isas', [])
1273main.Alias('#all-deps', '#all-isas')
1274
1275# Dummy target to ensure all environments are created before telling
1276# SCons what to actually make (the command line arguments).  We attach
1277# them to the dependence graph after the environments are complete.
1278ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1279def environsComplete(target, source, env):
1280    for t in ORIG_BUILD_TARGETS:
1281        main.Depends('#all-targets', t)
1282
1283# Each build/* switching_dir attaches its *-environs target to #all-environs.
1284main.Append(BUILDERS = {'CompleteEnvirons' :
1285                        Builder(action=MakeAction(environsComplete, None))})
1286main.CompleteEnvirons('#all-environs', [])
1287
1288def doNothing(**ignored): pass
1289main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1290
1291# The final target to which all the original targets ultimately get attached.
1292main.Dummy('#all-targets', '#all-environs')
1293BUILD_TARGETS[:] = ['#all-targets']
1294
1295###################################################
1296#
1297# Define build environments for selected configurations.
1298#
1299###################################################
1300
1301for variant_path in variant_paths:
1302    if not GetOption('silent'):
1303        print "Building in", variant_path
1304
1305    # Make a copy of the build-root environment to use for this config.
1306    env = main.Clone()
1307    env['BUILDDIR'] = variant_path
1308
1309    # variant_dir is the tail component of build path, and is used to
1310    # determine the build parameters (e.g., 'ALPHA_SE')
1311    (build_root, variant_dir) = splitpath(variant_path)
1312
1313    # Set env variables according to the build directory config.
1314    sticky_vars.files = []
1315    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1316    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1317    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1318    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1319    if isfile(current_vars_file):
1320        sticky_vars.files.append(current_vars_file)
1321        if not GetOption('silent'):
1322            print "Using saved variables file %s" % current_vars_file
1323    else:
1324        # Build dir-specific variables file doesn't exist.
1325
1326        # Make sure the directory is there so we can create it later
1327        opt_dir = dirname(current_vars_file)
1328        if not isdir(opt_dir):
1329            mkdir(opt_dir)
1330
1331        # Get default build variables from source tree.  Variables are
1332        # normally determined by name of $VARIANT_DIR, but can be
1333        # overridden by '--default=' arg on command line.
1334        default = GetOption('default')
1335        opts_dir = joinpath(main.root.abspath, 'build_opts')
1336        if default:
1337            default_vars_files = [joinpath(build_root, 'variables', default),
1338                                  joinpath(opts_dir, default)]
1339        else:
1340            default_vars_files = [joinpath(opts_dir, variant_dir)]
1341        existing_files = filter(isfile, default_vars_files)
1342        if existing_files:
1343            default_vars_file = existing_files[0]
1344            sticky_vars.files.append(default_vars_file)
1345            print "Variables file %s not found,\n  using defaults in %s" \
1346                  % (current_vars_file, default_vars_file)
1347        else:
1348            print "Error: cannot find variables file %s or " \
1349                  "default file(s) %s" \
1350                  % (current_vars_file, ' or '.join(default_vars_files))
1351            Exit(1)
1352
1353    # Apply current variable settings to env
1354    sticky_vars.Update(env)
1355
1356    help_texts["local_vars"] += \
1357        "Build variables for %s:\n" % variant_dir \
1358                 + sticky_vars.GenerateHelpText(env)
1359
1360    # Process variable settings.
1361
1362    if not have_fenv and env['USE_FENV']:
1363        print "Warning: <fenv.h> not available; " \
1364              "forcing USE_FENV to False in", variant_dir + "."
1365        env['USE_FENV'] = False
1366
1367    if not env['USE_FENV']:
1368        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1369        print "         FP results may deviate slightly from other platforms."
1370
1371    if env['EFENCE']:
1372        env.Append(LIBS=['efence'])
1373
1374    if env['USE_KVM']:
1375        if not have_kvm:
1376            print "Warning: Can not enable KVM, host seems to lack KVM support"
1377            env['USE_KVM'] = False
1378        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1379            print "Info: KVM support disabled due to unsupported host and " \
1380                "target ISA combination"
1381            env['USE_KVM'] = False
1382
1383    # Warn about missing optional functionality
1384    if env['USE_KVM']:
1385        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1386            print "Warning: perf_event headers lack support for the " \
1387                "exclude_host attribute. KVM instruction counts will " \
1388                "be inaccurate."
1389
1390    # Save sticky variable settings back to current variables file
1391    sticky_vars.Save(current_vars_file, env)
1392
1393    if env['USE_SSE2']:
1394        env.Append(CCFLAGS=['-msse2'])
1395
1396    # The src/SConscript file sets up the build rules in 'env' according
1397    # to the configured variables.  It returns a list of environments,
1398    # one for each variant build (debug, opt, etc.)
1399    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1400
1401def pairwise(iterable):
1402    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1403    a, b = itertools.tee(iterable)
1404    b.next()
1405    return itertools.izip(a, b)
1406
1407# Create false dependencies so SCons will parse ISAs, establish
1408# dependencies, and setup the build Environments serially. Either
1409# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1410# greater than 1. It appears to be standard race condition stuff; it
1411# doesn't always fail, but usually, and the behaviors are different.
1412# Every time I tried to remove this, builds would fail in some
1413# creative new way. So, don't do that. You'll want to, though, because
1414# tests/SConscript takes a long time to make its Environments.
1415for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1416    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1417    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1418
1419# base help text
1420Help('''
1421Usage: scons [scons options] [build variables] [target(s)]
1422
1423Extra scons options:
1424%(options)s
1425
1426Global build variables:
1427%(global_vars)s
1428
1429%(local_vars)s
1430''' % help_texts)
1431