SConstruct revision 9900
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2013 ARM Limited
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
79812Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
89812Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
99812Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
109812Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
119812Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
129812Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
139812Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
149812Sandreas.hansson@arm.com#
157816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
165871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
171762SN/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.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "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,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
445863Snate@binkert.org#          Nathan Binkert
45955SN/A
46955SN/A###################################################
47955SN/A#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
508878Ssteve.reinhardt@amd.com# While in this directory ('gem5'), just type 'scons' to build the default
512632Sstever@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
532632Sstever@eecs.umich.edu# the optimized full-system version).
54955SN/A#
558878Ssteve.reinhardt@amd.com# You can build gem5 in a different directory as long as there is a
562632Sstever@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
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632761Sstever@eecs.umich.edu#   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
658878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
682761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
692761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
702761Sstever@eecs.umich.edu#   file.
718878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728878Ssteve.reinhardt@amd.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732632Sstever@eecs.umich.edu#
742632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
758878Ssteve.reinhardt@amd.com# 'gem5' directory (or use -u or -C to tell scons where to find this
768878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
772632Sstever@eecs.umich.edu# options as well.
78955SN/A#
79955SN/A###################################################
80955SN/A
8112563Sgabeblack@google.com# Check for recent-enough Python and SCons versions.
8212563Sgabeblack@google.comtry:
836654Snate@binkert.org    # Really old versions of scons only take two options for the
8410196SCurtis.Dunham@arm.com    # function, so check once without the revision and once with the
85955SN/A    # revision, the first instance will fail for stuff other than
865396Ssaidi@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
8711401Sandreas.sandberg@arm.com    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
904202Sbinkertn@umich.edu    print """
915863Snate@binkert.orgFor more details, see:
925863Snate@binkert.org    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
95955SN/A
966654Snate@binkert.org# We ensure the python version early because because python-config
975273Sstever@gmail.com# requires python 2.5
985871Snate@binkert.orgtry:
995273Sstever@gmail.com    EnsurePythonVersion(2, 5)
1006654Snate@binkert.orgexcept SystemExit, e:
1015396Ssaidi@eecs.umich.edu    print """
1028120Sgblack@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1038120Sgblack@eecs.umich.edurearranging your PATH so that scons finds the non-default 'python' and
1048120Sgblack@eecs.umich.edu'python-config' first.
1058120Sgblack@eecs.umich.edu
1068120Sgblack@eecs.umich.eduFor more details, see:
1078120Sgblack@eecs.umich.edu    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1088120Sgblack@eecs.umich.edu"""
1098120Sgblack@eecs.umich.edu    raise
1108879Ssteve.reinhardt@amd.com
1118879Ssteve.reinhardt@amd.com# Global Python includes
1128879Ssteve.reinhardt@amd.comimport os
1138879Ssteve.reinhardt@amd.comimport re
1148879Ssteve.reinhardt@amd.comimport subprocess
1158879Ssteve.reinhardt@amd.comimport sys
1168879Ssteve.reinhardt@amd.com
1178879Ssteve.reinhardt@amd.comfrom os import mkdir, environ
1188879Ssteve.reinhardt@amd.comfrom os.path import abspath, basename, dirname, expanduser, normpath
1198879Ssteve.reinhardt@amd.comfrom os.path import exists,  isdir, isfile
1208879Ssteve.reinhardt@amd.comfrom os.path import join as joinpath, split as splitpath
1218879Ssteve.reinhardt@amd.com
1228879Ssteve.reinhardt@amd.com# SCons includes
1238120Sgblack@eecs.umich.eduimport SCons
1248120Sgblack@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
1338120Sgblack@eecs.umich.edufrom m5.util import compareVersions, readCommand
1348120Sgblack@eecs.umich.edufrom m5.util.terminal import get_termcap
1358120Sgblack@eecs.umich.edu
1368120Sgblack@eecs.umich.eduhelp_texts = {
1378879Ssteve.reinhardt@amd.com    "options" : "",
1388879Ssteve.reinhardt@amd.com    "global_vars" : "",
1398879Ssteve.reinhardt@amd.com    "local_vars" : ""
1408879Ssteve.reinhardt@amd.com}
14110458Sandreas.hansson@arm.com
14210458Sandreas.hansson@arm.comExport("help_texts")
14310458Sandreas.hansson@arm.com
1448879Ssteve.reinhardt@amd.com
1458879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1468879Ssteve.reinhardt@amd.com# AddOption() are supposed to be displayed when you type 'scons -h'
1478879Ssteve.reinhardt@amd.com# and (2) you can override the help displayed by 'scons -h' using the
14813421Sciro.santilli@arm.com# Help() function, but these two features are incompatible: once
14913421Sciro.santilli@arm.com# you've overridden the help text using Help(), there's no way to get
1509227Sandreas.hansson@arm.com# at the help texts from AddOptions.  See:
1519227Sandreas.hansson@arm.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
15212063Sgabeblack@google.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
15312063Sgabeblack@google.com# This hack lets us extract the help text from AddOptions and
15412063Sgabeblack@google.com# re-inject it via Help().  Ideally someday this bug will be fixed and
1558879Ssteve.reinhardt@amd.com# we can just use AddOption directly.
1568879Ssteve.reinhardt@amd.comdef AddLocalOption(*args, **kwargs):
1578879Ssteve.reinhardt@amd.com    col_width = 30
1588879Ssteve.reinhardt@amd.com
15910453SAndrew.Bardsley@arm.com    help = "  " + ", ".join(args)
16010453SAndrew.Bardsley@arm.com    if "help" in kwargs:
16110453SAndrew.Bardsley@arm.com        length = len(help)
16210456SCurtis.Dunham@arm.com        if length >= col_width:
16310456SCurtis.Dunham@arm.com            help += "\n" + " " * col_width
16410456SCurtis.Dunham@arm.com        else:
16510457Sandreas.hansson@arm.com            help += " " * (col_width - length)
16610457Sandreas.hansson@arm.com        help += kwargs["help"]
16711342Sandreas.hansson@arm.com    help_texts["options"] += help + "\n"
16811342Sandreas.hansson@arm.com
1698120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
17012063Sgabeblack@google.com
17112563Sgabeblack@google.comAddLocalOption('--colors', dest='use_colors', action='store_true',
17212063Sgabeblack@google.com               help="Add color to abbreviated scons output")
17312063Sgabeblack@google.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1745871Snate@binkert.org               help="Don't add color to abbreviated scons output")
1755871Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1766121Snate@binkert.org               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')
1799926Sstan.czerniawski@arm.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
18012243Sgabeblack@google.com               help='Disable Link-Time Optimization for fast')
1811533SN/AAddLocalOption('--update-ref', dest='update_ref', action='store_true',
18212246Sgabeblack@google.com               help='Update test reference outputs')
18312246Sgabeblack@google.comAddLocalOption('--verbose', dest='verbose', action='store_true',
18412246Sgabeblack@google.com               help='Print full tool command lines')
18512246Sgabeblack@google.com
1869239Sandreas.hansson@arm.comtermcap = get_termcap(GetOption('use_colors'))
1879239Sandreas.hansson@arm.com
1889239Sandreas.hansson@arm.com########################################################################
1899239Sandreas.hansson@arm.com#
19012563Sgabeblack@google.com# Set up the main build environment.
1919239Sandreas.hansson@arm.com#
1929239Sandreas.hansson@arm.com########################################################################
193955SN/Ause_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
194955SN/A                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1952632Sstever@eecs.umich.edu                 'RANLIB', 'SWIG' ])
1962632Sstever@eecs.umich.edu
197955SN/Ause_prefixes = [
198955SN/A    "M5",           # M5 configuration (e.g., path to kernels)
199955SN/A    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
200955SN/A    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2018878Ssteve.reinhardt@amd.com    "CCC_",         # clang static analyzer configuration
202955SN/A    ]
2032632Sstever@eecs.umich.edu
2042632Sstever@eecs.umich.eduuse_env = {}
2052632Sstever@eecs.umich.edufor key,val in os.environ.iteritems():
2062632Sstever@eecs.umich.edu    if key in use_vars or \
2072632Sstever@eecs.umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
2082632Sstever@eecs.umich.edu        use_env[key] = val
2092632Sstever@eecs.umich.edu
2108268Ssteve.reinhardt@amd.commain = Environment(ENV=use_env)
2118268Ssteve.reinhardt@amd.commain.Decider('MD5-timestamp')
2128268Ssteve.reinhardt@amd.commain.root = Dir(".")         # The current directory (where this file lives).
2138268Ssteve.reinhardt@amd.commain.srcdir = Dir("src")     # The source directory
2148268Ssteve.reinhardt@amd.com
2158268Ssteve.reinhardt@amd.commain_dict_keys = main.Dictionary().keys()
2168268Ssteve.reinhardt@amd.com
2172632Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
2182632Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2192632Sstever@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2202632Sstever@eecs.umich.edu    Exit(1)
2218268Ssteve.reinhardt@amd.com
2222632Sstever@eecs.umich.edu# Check that swig is present
2238268Ssteve.reinhardt@amd.comif not 'SWIG' in main_dict_keys:
2248268Ssteve.reinhardt@amd.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
2258268Ssteve.reinhardt@amd.com    Exit(1)
2268268Ssteve.reinhardt@amd.com
2273718Sstever@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2282634Sstever@eecs.umich.edu# as well
2292634Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2305863Snate@binkert.org
2312638Sstever@eecs.umich.edu########################################################################
2328268Ssteve.reinhardt@amd.com#
2332632Sstever@eecs.umich.edu# Mercurial Stuff.
2342632Sstever@eecs.umich.edu#
2352632Sstever@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2362632Sstever@eecs.umich.edu# extra things.
23712563Sgabeblack@google.com#
2381858SN/A########################################################################
2393716Sstever@eecs.umich.edu
2402638Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2412638Sstever@eecs.umich.edu
2422638Sstever@eecs.umich.edumercurial_style_message = """
2432638Sstever@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
24412563Sgabeblack@google.comagainst the gem5 style rules on hg commit and qrefresh commands.  This
24512563Sgabeblack@google.comscript will now install the hook in your .hg/hgrc file.
2462638Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2475863Snate@binkert.org
2485863Snate@binkert.orgmercurial_style_hook = """
2495863Snate@binkert.org# The following lines were automatically added by gem5/SConstruct
250955SN/A# to provide the gem5 style-checking hooks
2515341Sstever@gmail.com[extensions]
2525341Sstever@gmail.comstyle = %s/util/style.py
2535863Snate@binkert.org
2547756SAli.Saidi@ARM.com[hooks]
2555341Sstever@gmail.compretxncommit.style = python:style.check_style
2566121Snate@binkert.orgpre-qrefresh.style = python:style.check_style
2574494Ssaidi@eecs.umich.edu# End of SConstruct additions
2586121Snate@binkert.org
2591105SN/A""" % (main.root.abspath)
2602667Sstever@eecs.umich.edu
2612667Sstever@eecs.umich.edumercurial_lib_not_found = """
2622667Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook.  If
2632667Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
2646121Snate@binkert.orghook. It is important.
2652667Sstever@eecs.umich.edu"""
2665341Sstever@gmail.com
2675863Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
2685341Sstever@gmail.com# Skip this if --ignore-style was specified, there's no .hg dir to
2695341Sstever@gmail.com# install a hook in, or there's no interactive terminal to prompt.
2705341Sstever@gmail.comif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2718120Sgblack@eecs.umich.edu    style_hook = True
2725341Sstever@gmail.com    try:
2738120Sgblack@eecs.umich.edu        from mercurial import ui
2745341Sstever@gmail.com        ui = ui.ui()
2758120Sgblack@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2766121Snate@binkert.org        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2776121Snate@binkert.org                     ui.config('hooks', 'pre-qrefresh.style', None)
2789396Sandreas.hansson@arm.com    except ImportError:
2795397Ssaidi@eecs.umich.edu        print mercurial_lib_not_found
2805397Ssaidi@eecs.umich.edu
2817727SAli.Saidi@ARM.com    if not style_hook:
2828268Ssteve.reinhardt@amd.com        print mercurial_style_message,
2836168Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
2845341Sstever@gmail.com        try:
2858120Sgblack@eecs.umich.edu            raw_input()
2868120Sgblack@eecs.umich.edu        except:
2878120Sgblack@eecs.umich.edu            print "Input exception, exiting scons.\n"
2886814Sgblack@eecs.umich.edu            sys.exit(1)
2895863Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2908120Sgblack@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
2915341Sstever@gmail.com        try:
2925863Snate@binkert.org            hgrc = open(hgrc_path, 'a')
2938268Ssteve.reinhardt@amd.com            hgrc.write(mercurial_style_hook)
2946121Snate@binkert.org            hgrc.close()
2956121Snate@binkert.org        except:
2968268Ssteve.reinhardt@amd.com            print "Error updating", hgrc_path
2975742Snate@binkert.org            sys.exit(1)
2985742Snate@binkert.org
2995341Sstever@gmail.com
3005742Snate@binkert.org###################################################
3015742Snate@binkert.org#
3025341Sstever@gmail.com# Figure out which configurations to set up based on the path(s) of
3036017Snate@binkert.org# the target(s).
3046121Snate@binkert.org#
3056017Snate@binkert.org###################################################
30612158Sandreas.sandberg@arm.com
30712158Sandreas.sandberg@arm.com# Find default configuration & binary.
30812158Sandreas.sandberg@arm.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3098120Sgblack@eecs.umich.edu
3107756SAli.Saidi@ARM.com# helper function: find last occurrence of element in list
3117756SAli.Saidi@ARM.comdef rfind(l, elt, offs = -1):
3127756SAli.Saidi@ARM.com    for i in range(len(l)+offs, 0, -1):
3137756SAli.Saidi@ARM.com        if l[i] == elt:
3147816Ssteve.reinhardt@amd.com            return i
3157816Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
3167816Ssteve.reinhardt@amd.com
3177816Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
3187816Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
31911979Sgabeblack@google.com# relative to the launch directory unless a different root is provided
3207816Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3217816Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
3227816Ssteve.reinhardt@amd.com            for p in path_list]
3237816Ssteve.reinhardt@amd.com
3247756SAli.Saidi@ARM.com# Each target must have 'build' in the interior of the path; the
3257756SAli.Saidi@ARM.com# directory below this will determine the build parameters.  For
3269227Sandreas.hansson@arm.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3279227Sandreas.hansson@arm.com# recognize that ALPHA_SE specifies the configuration because it
3289227Sandreas.hansson@arm.com# follow 'build' in the build path.
3299227Sandreas.hansson@arm.com
3309590Sandreas@sandberg.pp.se# The funky assignment to "[:]" is needed to replace the list contents
3319590Sandreas@sandberg.pp.se# in place rather than reassign the symbol to a new list, which
3329590Sandreas@sandberg.pp.se# doesn't work (obviously!).
3339590Sandreas@sandberg.pp.seBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3349590Sandreas@sandberg.pp.se
3359590Sandreas@sandberg.pp.se# Generate a list of the unique build roots and configs that the
3366654Snate@binkert.org# collected targets reference.
3376654Snate@binkert.orgvariant_paths = []
3385871Snate@binkert.orgbuild_root = None
3396121Snate@binkert.orgfor t in BUILD_TARGETS:
3408946Sandreas.hansson@arm.com    path_dirs = t.split('/')
3419419Sandreas.hansson@arm.com    try:
34212563Sgabeblack@google.com        build_top = rfind(path_dirs, 'build', -2)
3433918Ssaidi@eecs.umich.edu    except:
3443918Ssaidi@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3451858SN/A        Exit(1)
3469556Sandreas.hansson@arm.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3479556Sandreas.hansson@arm.com    if not build_root:
3489556Sandreas.hansson@arm.com        build_root = this_build_root
3499556Sandreas.hansson@arm.com    else:
35011294Sandreas.hansson@arm.com        if this_build_root != build_root:
35111294Sandreas.hansson@arm.com            print "Error: build targets not under same build root\n"\
35211294Sandreas.hansson@arm.com                  "  %s\n  %s" % (build_root, this_build_root)
35311294Sandreas.hansson@arm.com            Exit(1)
35410878Sandreas.hansson@arm.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
35510878Sandreas.hansson@arm.com    if variant_path not in variant_paths:
35611811Sbaz21@cam.ac.uk        variant_paths.append(variant_path)
35711811Sbaz21@cam.ac.uk
35811811Sbaz21@cam.ac.uk# Make sure build_root exists (might not if this is the first build there)
35911982Sgabeblack@google.comif not isdir(build_root):
36011982Sgabeblack@google.com    mkdir(build_root)
36111982Sgabeblack@google.commain['BUILDROOT'] = build_root
36213421Sciro.santilli@arm.com
36313421Sciro.santilli@arm.comExport('main')
36411982Sgabeblack@google.com
36511992Sgabeblack@google.commain.SConsignFile(joinpath(build_root, "sconsign"))
36611982Sgabeblack@google.com
36711982Sgabeblack@google.com# Default duplicate option is to use hard links, but this messes up
36812305Sgabeblack@google.com# when you use emacs to edit a file in the target dir, as emacs moves
36912305Sgabeblack@google.com# file to file~ then copies to file, breaking the link.  Symbolic
37012305Sgabeblack@google.com# (soft) links work better.
37112305Sgabeblack@google.commain.SetOption('duplicate', 'soft-copy')
37212305Sgabeblack@google.com
37312305Sgabeblack@google.com#
37412305Sgabeblack@google.com# Set up global sticky variables... these are common to an entire build
3759556Sandreas.hansson@arm.com# tree (not specific to a particular build like ALPHA_SE)
37612563Sgabeblack@google.com#
37712563Sgabeblack@google.com
37812563Sgabeblack@google.comglobal_vars_file = joinpath(build_root, 'variables.global')
37912563Sgabeblack@google.com
3809556Sandreas.hansson@arm.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
38112563Sgabeblack@google.com
38212563Sgabeblack@google.comglobal_vars.AddVariables(
3839556Sandreas.hansson@arm.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
38412563Sgabeblack@google.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
38512563Sgabeblack@google.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
38612563Sgabeblack@google.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
38712563Sgabeblack@google.com    ('BATCH', 'Use batch pool for build and tests', False),
38812563Sgabeblack@google.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
38912563Sgabeblack@google.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
39012563Sgabeblack@google.com    ('EXTRAS', 'Add extra directories to the compilation', '')
39112563Sgabeblack@google.com    )
3929556Sandreas.hansson@arm.com
3939556Sandreas.hansson@arm.com# Update main environment with values from ARGUMENTS & global_vars_file
3946121Snate@binkert.orgglobal_vars.Update(main)
39511500Sandreas.hansson@arm.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
39610238Sandreas.hansson@arm.com
39710878Sandreas.hansson@arm.com# Save sticky variable settings back to current variables file
3989420Sandreas.hansson@arm.comglobal_vars.Save(global_vars_file, main)
39911500Sandreas.hansson@arm.com
40012563Sgabeblack@google.com# Parse EXTRAS variable to build list of all directories where we're
40112563Sgabeblack@google.com# look for sources etc.  This list is exported as extras_dir_list.
4029420Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
4039420Sandreas.hansson@arm.comif main['EXTRAS']:
4049420Sandreas.hansson@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4059420Sandreas.hansson@arm.comelse:
40612063Sgabeblack@google.com    extras_dir_list = []
40712063Sgabeblack@google.com
40812063Sgabeblack@google.comExport('base_dir')
40912063Sgabeblack@google.comExport('extras_dir_list')
41012063Sgabeblack@google.com
41112063Sgabeblack@google.com# the ext directory should be on the #includes path
41212063Sgabeblack@google.commain.Append(CPPPATH=[Dir('ext')])
41312063Sgabeblack@google.com
41412063Sgabeblack@google.comdef strip_build_path(path, env):
41512063Sgabeblack@google.com    path = str(path)
41612063Sgabeblack@google.com    variant_base = env['BUILDROOT'] + os.path.sep
41712063Sgabeblack@google.com    if path.startswith(variant_base):
41812063Sgabeblack@google.com        path = path[len(variant_base):]
41912063Sgabeblack@google.com    elif path.startswith('build/'):
42012063Sgabeblack@google.com        path = path[6:]
42112063Sgabeblack@google.com    return path
42212063Sgabeblack@google.com
42312063Sgabeblack@google.com# Generate a string of the form:
42412063Sgabeblack@google.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
42512063Sgabeblack@google.com# to print while building.
42612063Sgabeblack@google.comclass Transform(object):
42712063Sgabeblack@google.com    # all specific color settings should be here and nowhere else
42810457Sandreas.hansson@arm.com    tool_color = termcap.Normal
42910457Sandreas.hansson@arm.com    pfx_color = termcap.Yellow
43010457Sandreas.hansson@arm.com    srcs_color = termcap.Yellow + termcap.Bold
43110457Sandreas.hansson@arm.com    arrow_color = termcap.Blue + termcap.Bold
43210457Sandreas.hansson@arm.com    tgts_color = termcap.Yellow + termcap.Bold
43312563Sgabeblack@google.com
43412563Sgabeblack@google.com    def __init__(self, tool, max_sources=99):
43512563Sgabeblack@google.com        self.format = self.tool_color + (" [%8s] " % tool) \
43610457Sandreas.hansson@arm.com                      + self.pfx_color + "%s" \
43712063Sgabeblack@google.com                      + self.srcs_color + "%s" \
43812063Sgabeblack@google.com                      + self.arrow_color + " -> " \
43912063Sgabeblack@google.com                      + self.tgts_color + "%s" \
44012563Sgabeblack@google.com                      + termcap.Normal
44112563Sgabeblack@google.com        self.max_sources = max_sources
44212563Sgabeblack@google.com
44312563Sgabeblack@google.com    def __call__(self, target, source, env, for_signature=None):
44412563Sgabeblack@google.com        # truncate source list according to max_sources param
44512563Sgabeblack@google.com        source = source[0:self.max_sources]
44612063Sgabeblack@google.com        def strip(f):
44712063Sgabeblack@google.com            return strip_build_path(str(f), env)
44810238Sandreas.hansson@arm.com        if len(source) > 0:
44910238Sandreas.hansson@arm.com            srcs = map(strip, source)
45010238Sandreas.hansson@arm.com        else:
45112063Sgabeblack@google.com            srcs = ['']
45210238Sandreas.hansson@arm.com        tgts = map(strip, target)
45310238Sandreas.hansson@arm.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
45410416Sandreas.hansson@arm.com        # operation that has nothing to do with paths.
45510238Sandreas.hansson@arm.com        com_pfx = os.path.commonprefix(srcs + tgts)
4569227Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
45710238Sandreas.hansson@arm.com        if com_pfx:
45810416Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
45910416Sandreas.hansson@arm.com            if com_pfx[-1] == ".":
4609227Sandreas.hansson@arm.com                # prefix matches all but file extension: ok
4619590Sandreas@sandberg.pp.se                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4629590Sandreas@sandberg.pp.se                com_pfx = com_pfx[0:-1]
4639590Sandreas@sandberg.pp.se            elif com_pfx[-1] == "/":
46412304Sgabeblack@google.com                # common prefix is directory path: OK
46512304Sgabeblack@google.com                pass
46612304Sgabeblack@google.com            else:
46712688Sgiacomo.travaglini@arm.com                src0_len = len(srcs[0])
46812688Sgiacomo.travaglini@arm.com                tgt0_len = len(tgts[0])
46912688Sgiacomo.travaglini@arm.com                if src0_len == com_pfx_len:
47013020Sshunhsingou@google.com                    # source is a substring of target, OK
47112304Sgabeblack@google.com                    pass
47212688Sgiacomo.travaglini@arm.com                elif tgt0_len == com_pfx_len:
47312688Sgiacomo.travaglini@arm.com                    # target is a substring of source, need to back up to
47413020Sshunhsingou@google.com                    # avoid empty string on RHS of arrow
47512304Sgabeblack@google.com                    sep_idx = com_pfx.rfind(".")
47612304Sgabeblack@google.com                    if sep_idx != -1:
47712304Sgabeblack@google.com                        com_pfx = com_pfx[0:sep_idx]
47812304Sgabeblack@google.com                    else:
47912688Sgiacomo.travaglini@arm.com                        com_pfx = ''
48012688Sgiacomo.travaglini@arm.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
48112688Sgiacomo.travaglini@arm.com                    # still splitting at file extension: ok
48212304Sgabeblack@google.com                    pass
4838737Skoansin.tan@gmail.com                else:
48410878Sandreas.hansson@arm.com                    # probably a fluke; ignore it
48511500Sandreas.hansson@arm.com                    com_pfx = ''
4869420Sandreas.hansson@arm.com        # recalculate length in case com_pfx was modified
4878737Skoansin.tan@gmail.com        com_pfx_len = len(com_pfx)
48810106SMitch.Hayenga@arm.com        def fmt(files):
4898737Skoansin.tan@gmail.com            f = map(lambda s: s[com_pfx_len:], files)
4908737Skoansin.tan@gmail.com            return ', '.join(f)
49110878Sandreas.hansson@arm.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
49212563Sgabeblack@google.com
49312563Sgabeblack@google.comExport('Transform')
4948737Skoansin.tan@gmail.com
4958737Skoansin.tan@gmail.com# enable the regression script to use the termcap
49612563Sgabeblack@google.commain['TERMCAP'] = termcap
4978737Skoansin.tan@gmail.com
4988737Skoansin.tan@gmail.comif GetOption('verbose'):
49911294Sandreas.hansson@arm.com    def MakeAction(action, string, *args, **kwargs):
5009556Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
5019556Sandreas.hansson@arm.comelse:
5029556Sandreas.hansson@arm.com    MakeAction = Action
50311294Sandreas.hansson@arm.com    main['CCCOMSTR']        = Transform("CC")
50410278SAndreas.Sandberg@ARM.com    main['CXXCOMSTR']       = Transform("CXX")
50510278SAndreas.Sandberg@ARM.com    main['ASCOMSTR']        = Transform("AS")
50610278SAndreas.Sandberg@ARM.com    main['SWIGCOMSTR']      = Transform("SWIG")
50710278SAndreas.Sandberg@ARM.com    main['ARCOMSTR']        = Transform("AR", 0)
50810278SAndreas.Sandberg@ARM.com    main['LINKCOMSTR']      = Transform("LINK", 0)
50910278SAndreas.Sandberg@ARM.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5109556Sandreas.hansson@arm.com    main['M4COMSTR']        = Transform("M4")
5119590Sandreas@sandberg.pp.se    main['SHCCCOMSTR']      = Transform("SHCC")
5129590Sandreas@sandberg.pp.se    main['SHCXXCOMSTR']     = Transform("SHCXX")
5139420Sandreas.hansson@arm.comExport('MakeAction')
5149846Sandreas.hansson@arm.com
5159846Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
5169846Sandreas.hansson@arm.commain['LTO_CCFLAGS'] = []
5179846Sandreas.hansson@arm.commain['LTO_LDFLAGS'] = []
5188946Sandreas.hansson@arm.com
51911811Sbaz21@cam.ac.uk# According to the readme, tcmalloc works best if the compiler doesn't
52011811Sbaz21@cam.ac.uk# assume that we're using the builtin malloc and friends. These flags
52111811Sbaz21@cam.ac.uk# are compiler-specific, so we need to set them after we detect which
52211811Sbaz21@cam.ac.uk# compiler we're using.
52312304Sgabeblack@google.commain['TCMALLOC_CCFLAGS'] = []
52412304Sgabeblack@google.com
52512304Sgabeblack@google.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
52612304Sgabeblack@google.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
52713020Sshunhsingou@google.com
52813020Sshunhsingou@google.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
52912304Sgabeblack@google.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
53012304Sgabeblack@google.comif main['GCC'] + main['CLANG'] > 1:
53113020Sshunhsingou@google.com    print 'Error: How can we have two at the same time?'
53213020Sshunhsingou@google.com    Exit(1)
53312304Sgabeblack@google.com
53412304Sgabeblack@google.com# Set up default C++ compiler flags
53513020Sshunhsingou@google.comif main['GCC'] or main['CLANG']:
53613020Sshunhsingou@google.com    # As gcc and clang share many flags, do the common parts here
53712304Sgabeblack@google.com    main.Append(CCFLAGS=['-pipe'])
53812304Sgabeblack@google.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5393918Ssaidi@eecs.umich.edu    # Enable -Wall and then disable the few warnings that we
54012563Sgabeblack@google.com    # consistently violate
54112563Sgabeblack@google.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
54212563Sgabeblack@google.com    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
54312563Sgabeblack@google.com    # actually use that name, so we stick with c++0x
5449068SAli.Saidi@ARM.com    main.Append(CXXFLAGS=['-std=c++0x'])
54512563Sgabeblack@google.com    # Add selected sanity checks from -Wextra
54612563Sgabeblack@google.com    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5479068SAli.Saidi@ARM.com                          '-Woverloaded-virtual'])
54812563Sgabeblack@google.comelse:
54912563Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
55012563Sgabeblack@google.com    print "Don't know what compiler options to use for your compiler."
55112563Sgabeblack@google.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
55212563Sgabeblack@google.com    print termcap.Yellow + '       version:' + termcap.Normal,
55312563Sgabeblack@google.com    if not CXX_version:
55412563Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
55512563Sgabeblack@google.com               termcap.Normal
5563918Ssaidi@eecs.umich.edu    else:
5573918Ssaidi@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
5586157Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
5596157Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
5606157Snate@binkert.org    print "       environment."
5616157Snate@binkert.org    print "       "
5625397Ssaidi@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5635397Ssaidi@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
5646121Snate@binkert.org    print "       src/SConscript to support that compiler."
5656121Snate@binkert.org    Exit(1)
5666121Snate@binkert.org
5676121Snate@binkert.orgif main['GCC']:
5686121Snate@binkert.org    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5696121Snate@binkert.org    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5705397Ssaidi@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5711851SN/A    if compareVersions(gcc_version, "4.4") < 0:
5721851SN/A        print 'Error: gcc version 4.4 or newer required.'
5737739Sgblack@eecs.umich.edu        print '       Installed version:', gcc_version
574955SN/A        Exit(1)
5759396Sandreas.hansson@arm.com
5769396Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
5779396Sandreas.hansson@arm.com
5789396Sandreas.hansson@arm.com    # Check for versions with bugs
5799396Sandreas.hansson@arm.com    if not compareVersions(gcc_version, '4.4.1') or \
5809396Sandreas.hansson@arm.com       not compareVersions(gcc_version, '4.4.2'):
58112563Sgabeblack@google.com        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
58212563Sgabeblack@google.com        main.Append(CCFLAGS=['-fno-tree-vectorize'])
58312563Sgabeblack@google.com
58412563Sgabeblack@google.com    # LTO support is only really working properly from 4.6 and beyond
5859396Sandreas.hansson@arm.com    if compareVersions(gcc_version, '4.6') >= 0:
5869396Sandreas.hansson@arm.com        # Add the appropriate Link-Time Optimization (LTO) flags
5879396Sandreas.hansson@arm.com        # unless LTO is explicitly turned off. Note that these flags
5889396Sandreas.hansson@arm.com        # are only used by the fast target.
5899396Sandreas.hansson@arm.com        if not GetOption('no_lto'):
5909396Sandreas.hansson@arm.com            # Pass the LTO flag when compiling to produce GIMPLE
59112563Sgabeblack@google.com            # output, we merely create the flags here and only append
59212563Sgabeblack@google.com            # them later/
59312563Sgabeblack@google.com            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
59412563Sgabeblack@google.com
59512563Sgabeblack@google.com            # Use the same amount of jobs for LTO as we are running
5969477Sandreas.hansson@arm.com            # scons with, we hardcode the use of the linker plugin
5979477Sandreas.hansson@arm.com            # which requires either gold or GNU ld >= 2.21
5989477Sandreas.hansson@arm.com            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5999477Sandreas.hansson@arm.com                                   '-fuse-linker-plugin']
6009477Sandreas.hansson@arm.com
6019477Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6029477Sandreas.hansson@arm.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6039477Sandreas.hansson@arm.com
6049477Sandreas.hansson@arm.comelif main['CLANG']:
6059477Sandreas.hansson@arm.com    # Check for a supported version of clang, >= 2.9 is needed to
6069477Sandreas.hansson@arm.com    # support similar features as gcc 4.4. See
6079477Sandreas.hansson@arm.com    # http://clang.llvm.org/cxx_status.html for details
6089477Sandreas.hansson@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
6099477Sandreas.hansson@arm.com    clang_version_match = clang_version_re.match(CXX_version)
61012563Sgabeblack@google.com    if (clang_version_match):
61112563Sgabeblack@google.com        clang_version = clang_version_match.groups()[0]
61212563Sgabeblack@google.com        if compareVersions(clang_version, "2.9") < 0:
6139396Sandreas.hansson@arm.com            print 'Error: clang version 2.9 or newer required.'
6142667Sstever@eecs.umich.edu            print '       Installed version:', clang_version
61510710Sandreas.hansson@arm.com            Exit(1)
61610710Sandreas.hansson@arm.com    else:
61710710Sandreas.hansson@arm.com        print 'Error: Unable to determine clang version.'
61811811Sbaz21@cam.ac.uk        Exit(1)
61911811Sbaz21@cam.ac.uk
62011811Sbaz21@cam.ac.uk    # clang has a few additional warnings that we disable,
62111811Sbaz21@cam.ac.uk    # tautological comparisons are allowed due to unsigned integers
62211811Sbaz21@cam.ac.uk    # being compared to constants that happen to be 0, and extraneous
62311811Sbaz21@cam.ac.uk    # parantheses are allowed due to Ruby's printing of the AST,
62410710Sandreas.hansson@arm.com    # finally self assignments are allowed as the generated CPU code
62510710Sandreas.hansson@arm.com    # is relying on this
62610710Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-tautological-compare',
62710710Sandreas.hansson@arm.com                         '-Wno-parentheses',
62810384SCurtis.Dunham@arm.com                         '-Wno-self-assign'])
6299986Sandreas@sandberg.pp.se
6309986Sandreas@sandberg.pp.se    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6319986Sandreas@sandberg.pp.se
6329986Sandreas@sandberg.pp.se    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6339986Sandreas@sandberg.pp.se    # opposed to libstdc++, as the later is dated.
6349986Sandreas@sandberg.pp.se    if sys.platform == "darwin":
6359986Sandreas@sandberg.pp.se        main.Append(CXXFLAGS=['-stdlib=libc++'])
6369986Sandreas@sandberg.pp.se        main.Append(LIBS=['c++'])
6379986Sandreas@sandberg.pp.se
6389986Sandreas@sandberg.pp.seelse:
6399986Sandreas@sandberg.pp.se    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6409986Sandreas@sandberg.pp.se    print "Don't know what compiler options to use for your compiler."
6419986Sandreas@sandberg.pp.se    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6429986Sandreas@sandberg.pp.se    print termcap.Yellow + '       version:' + termcap.Normal,
6439986Sandreas@sandberg.pp.se    if not CXX_version:
6449986Sandreas@sandberg.pp.se        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6459986Sandreas@sandberg.pp.se               termcap.Normal
6469986Sandreas@sandberg.pp.se    else:
6479986Sandreas@sandberg.pp.se        print CXX_version.replace('\n', '<nl>')
6489986Sandreas@sandberg.pp.se    print "       If you're trying to use a compiler other than GCC"
6492638Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6502638Sstever@eecs.umich.edu    print "       environment."
6516121Snate@binkert.org    print "       "
6523716Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
6535522Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
6549986Sandreas@sandberg.pp.se    print "       src/SConscript to support that compiler."
6559986Sandreas@sandberg.pp.se    Exit(1)
6569986Sandreas@sandberg.pp.se
6575522Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
6585227Ssaidi@eecs.umich.edumain['YACCFLAGS'] = '-d'
6595227Ssaidi@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
6605227Ssaidi@eecs.umich.edu
6615227Ssaidi@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
6626654Snate@binkert.org# extra 'qdo' every time we run scons.
6636654Snate@binkert.orgif main['BATCH']:
6647769SAli.Saidi@ARM.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6657769SAli.Saidi@ARM.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6667769SAli.Saidi@ARM.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6677769SAli.Saidi@ARM.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6685227Ssaidi@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6695227Ssaidi@eecs.umich.edu
6705227Ssaidi@eecs.umich.eduif sys.platform == 'cygwin':
6715204Sstever@gmail.com    # cygwin has some header file issues...
6725204Sstever@gmail.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
6735204Sstever@gmail.com
6745204Sstever@gmail.com# Check for the protobuf compiler
6755204Sstever@gmail.comprotoc_version = readCommand([main['PROTOC'], '--version'],
6765204Sstever@gmail.com                             exception='').split()
6775204Sstever@gmail.com
6785204Sstever@gmail.com# First two words should be "libprotoc x.y.z"
6795204Sstever@gmail.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6805204Sstever@gmail.com    print termcap.Yellow + termcap.Bold + \
6815204Sstever@gmail.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6825204Sstever@gmail.com        '         Please install protobuf-compiler for tracing support.' + \
6835204Sstever@gmail.com        termcap.Normal
6845204Sstever@gmail.com    main['PROTOC'] = False
6855204Sstever@gmail.comelse:
6865204Sstever@gmail.com    # Based on the availability of the compress stream wrappers,
6875204Sstever@gmail.com    # require 2.1.0
6886121Snate@binkert.org    min_protoc_version = '2.1.0'
6895204Sstever@gmail.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6907727SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + \
6917727SAli.Saidi@ARM.com            'Warning: protoc version', min_protoc_version, \
69212563Sgabeblack@google.com            'or newer required.\n' + \
6937727SAli.Saidi@ARM.com            '         Installed version:', protoc_version[1], \
6947727SAli.Saidi@ARM.com            termcap.Normal
69511988Sandreas.sandberg@arm.com        main['PROTOC'] = False
69611988Sandreas.sandberg@arm.com    else:
69710453SAndrew.Bardsley@arm.com        # Attempt to determine the appropriate include path and
69810453SAndrew.Bardsley@arm.com        # library path using pkg-config, that means we also need to
69910453SAndrew.Bardsley@arm.com        # check for pkg-config. Note that it is possible to use
70010453SAndrew.Bardsley@arm.com        # protobuf without the involvement of pkg-config. Later on we
70110453SAndrew.Bardsley@arm.com        # check go a library config check and at that point the test
70210453SAndrew.Bardsley@arm.com        # will fail if libprotobuf cannot be found.
70310453SAndrew.Bardsley@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
70410453SAndrew.Bardsley@arm.com            try:
70510453SAndrew.Bardsley@arm.com                # Attempt to establish what linking flags to add for protobuf
70610453SAndrew.Bardsley@arm.com                # using pkg-config
70710160Sandreas.hansson@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
70810453SAndrew.Bardsley@arm.com            except:
70910453SAndrew.Bardsley@arm.com                print termcap.Yellow + termcap.Bold + \
71010453SAndrew.Bardsley@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
71110453SAndrew.Bardsley@arm.com                    termcap.Normal
71210453SAndrew.Bardsley@arm.com
71310453SAndrew.Bardsley@arm.com# Check for SWIG
71410453SAndrew.Bardsley@arm.comif not main.has_key('SWIG'):
71510453SAndrew.Bardsley@arm.com    print 'Error: SWIG utility not found.'
7169812Sandreas.hansson@arm.com    print '       Please install (see http://www.swig.org) and retry.'
71710453SAndrew.Bardsley@arm.com    Exit(1)
71810453SAndrew.Bardsley@arm.com
71910453SAndrew.Bardsley@arm.com# Check for appropriate SWIG version
72010453SAndrew.Bardsley@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
72110453SAndrew.Bardsley@arm.com# First 3 words should be "SWIG Version x.y.z"
72210453SAndrew.Bardsley@arm.comif len(swig_version) < 3 or \
72310453SAndrew.Bardsley@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
72410453SAndrew.Bardsley@arm.com    print 'Error determining SWIG version.'
72510453SAndrew.Bardsley@arm.com    Exit(1)
72610453SAndrew.Bardsley@arm.com
72710453SAndrew.Bardsley@arm.commin_swig_version = '1.3.34'
72810453SAndrew.Bardsley@arm.comif compareVersions(swig_version[2], min_swig_version) < 0:
7297727SAli.Saidi@ARM.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
73010453SAndrew.Bardsley@arm.com    print '       Installed version:', swig_version[2]
73110453SAndrew.Bardsley@arm.com    Exit(1)
73212790Smatteo.fusi@bsc.es
73312790Smatteo.fusi@bsc.es# Older versions of swig do not play well with more recent versions of
73412790Smatteo.fusi@bsc.es# gcc due to assumptions on implicit includes (cstddef) and use of
73512790Smatteo.fusi@bsc.es# namespaces
73612790Smatteo.fusi@bsc.esif main['GCC'] and compareVersions(gcc_version, '4.6') > 0 and \
73712790Smatteo.fusi@bsc.es        compareVersions(swig_version[2], '2') < 0:
73812790Smatteo.fusi@bsc.es    print '\n' + termcap.Yellow + termcap.Bold + \
73910453SAndrew.Bardsley@arm.com        'Warning: SWIG 1.x cause issues with gcc 4.6 and later.\n' + \
7403118Sstever@eecs.umich.edu        termcap.Normal + \
74110453SAndrew.Bardsley@arm.com        'Use SWIG 2.x to avoid assumptions on implicit includes\n' + \
74210453SAndrew.Bardsley@arm.com        'and use of namespaces\n'
74312563Sgabeblack@google.com
74410453SAndrew.Bardsley@arm.com# Set up SWIG flags & scanner
7453118Sstever@eecs.umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7463483Ssaidi@eecs.umich.edumain.Append(SWIGFLAGS=swig_flags)
7473494Ssaidi@eecs.umich.edu
7483494Ssaidi@eecs.umich.edu# filter out all existing swig scanners, they mess up the dependency
74912563Sgabeblack@google.com# stuff for some reason
7503483Ssaidi@eecs.umich.eduscanners = []
7513483Ssaidi@eecs.umich.edufor scanner in main['SCANNERS']:
7523053Sstever@eecs.umich.edu    skeys = scanner.skeys
7533053Sstever@eecs.umich.edu    if skeys == '.i':
7543918Ssaidi@eecs.umich.edu        continue
75512563Sgabeblack@google.com
75612563Sgabeblack@google.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
75712563Sgabeblack@google.com        continue
7583053Sstever@eecs.umich.edu
7593053Sstever@eecs.umich.edu    scanners.append(scanner)
7609396Sandreas.hansson@arm.com
7619396Sandreas.hansson@arm.com# add the new swig scanner that we like better
7629396Sandreas.hansson@arm.comfrom SCons.Scanner import ClassicCPP as CPPScanner
7639396Sandreas.hansson@arm.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7649396Sandreas.hansson@arm.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7659396Sandreas.hansson@arm.com
7669396Sandreas.hansson@arm.com# replace the scanners list that has what we want
7679396Sandreas.hansson@arm.commain['SCANNERS'] = scanners
7689396Sandreas.hansson@arm.com
76912920Sgabeblack@google.com# Add a custom Check function to the Configure context so that we can
77012920Sgabeblack@google.com# figure out if the compiler adds leading underscores to global
77112920Sgabeblack@google.com# variables.  This is needed for the autogenerated asm files that we
77212920Sgabeblack@google.com# use for embedding the python code.
7739477Sandreas.hansson@arm.comdef CheckLeading(context):
7749396Sandreas.hansson@arm.com    context.Message("Checking for leading underscore in global variables...")
77512563Sgabeblack@google.com    # 1) Define a global variable called x from asm so the C compiler
77612563Sgabeblack@google.com    #    won't change the symbol at all.
77712563Sgabeblack@google.com    # 2) Declare that variable.
77812563Sgabeblack@google.com    # 3) Use the variable
7799396Sandreas.hansson@arm.com    #
7807840Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
7817865Sgblack@eecs.umich.edu    # link because the external symbol 'x' will be called '_x' which
7827865Sgblack@eecs.umich.edu    # was defined by the asm statement.  If the compiler does not
7837865Sgblack@eecs.umich.edu    # prepend an underscore, this will not successfully link because
7847865Sgblack@eecs.umich.edu    # '_x' will have been defined by assembly, while the C portion of
7857865Sgblack@eecs.umich.edu    # the code will be trying to use 'x'
7867840Snate@binkert.org    ret = context.TryLink('''
7879900Sandreas@sandberg.pp.se        asm(".globl _x; _x: .byte 0");
7889900Sandreas@sandberg.pp.se        extern int x;
7899900Sandreas@sandberg.pp.se        int main() { return x; }
7909900Sandreas@sandberg.pp.se        ''', extension=".c")
79110456SCurtis.Dunham@arm.com    context.env.Append(LEADING_UNDERSCORE=ret)
79210456SCurtis.Dunham@arm.com    context.Result(ret)
79310456SCurtis.Dunham@arm.com    return ret
79410456SCurtis.Dunham@arm.com
79510456SCurtis.Dunham@arm.com# Platform-specific configuration.  Note again that we assume that all
79610456SCurtis.Dunham@arm.com# builds under a given build root run on the same host platform.
79712563Sgabeblack@google.comconf = Configure(main,
79812563Sgabeblack@google.com                 conf_dir = joinpath(build_root, '.scons_config'),
79912563Sgabeblack@google.com                 log_file = joinpath(build_root, 'scons_config.log'),
80012563Sgabeblack@google.com                 custom_tests = { 'CheckLeading' : CheckLeading })
8019045SAli.Saidi@ARM.com
80211235Sandreas.sandberg@arm.com# Check for leading underscores.  Don't really need to worry either
80311235Sandreas.sandberg@arm.com# way so don't need to check the return code.
80411235Sandreas.sandberg@arm.comconf.CheckLeading()
80511235Sandreas.sandberg@arm.com
80611235Sandreas.sandberg@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
80712485Sjang.hanhwi@gmail.comtry:
80812485Sjang.hanhwi@gmail.com    import platform
80912485Sjang.hanhwi@gmail.com    uname = platform.uname()
81011235Sandreas.sandberg@arm.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
81111811Sbaz21@cam.ac.uk        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
81212485Sjang.hanhwi@gmail.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
81311811Sbaz21@cam.ac.uk            main.Append(CFLAGS=['-arch', 'x86_64'])
81411811Sbaz21@cam.ac.uk            main.Append(LINKFLAGS=['-arch', 'x86_64'])
81511811Sbaz21@cam.ac.uk            main.Append(ASFLAGS=['-arch', 'x86_64'])
81611235Sandreas.sandberg@arm.comexcept:
81711235Sandreas.sandberg@arm.com    pass
81811235Sandreas.sandberg@arm.com
81912563Sgabeblack@google.com# Recent versions of scons substitute a "Null" object for Configure()
82012563Sgabeblack@google.com# when configuration isn't necessary, e.g., if the "--help" option is
82112563Sgabeblack@google.com# present.  Unfortuantely this Null object always returns false,
82211235Sandreas.sandberg@arm.com# breaking all our configuration checks.  We replace it with our own
8237840Snate@binkert.org# more optimistic null object that returns True instead.
82412563Sgabeblack@google.comif not conf:
8257840Snate@binkert.org    def NullCheck(*args, **kwargs):
8261858SN/A        return True
8271858SN/A
8281858SN/A    class NullConf:
82912563Sgabeblack@google.com        def __init__(self, env):
83012563Sgabeblack@google.com            self.env = env
8311858SN/A        def Finish(self):
83212230Sgiacomo.travaglini@arm.com            return self.env
83312230Sgiacomo.travaglini@arm.com        def __getattr__(self, mname):
83412230Sgiacomo.travaglini@arm.com            return NullCheck
83512230Sgiacomo.travaglini@arm.com
83612563Sgabeblack@google.com    conf = NullConf(main)
83712563Sgabeblack@google.com
83812563Sgabeblack@google.com# Cache build files in the supplied directory.
83912230Sgiacomo.travaglini@arm.comif main['M5_BUILD_CACHE']:
8409903Sandreas.hansson@arm.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
8419903Sandreas.hansson@arm.com    CacheDir(main['M5_BUILD_CACHE'])
8429903Sandreas.hansson@arm.com
8439903Sandreas.hansson@arm.com# Find Python include and library directories for embedding the
84410841Sandreas.sandberg@arm.com# interpreter. We rely on python-config to resolve the appropriate
8459651SAndreas.Sandberg@ARM.com# includes and linker flags. ParseConfig does not seem to understand
84612563Sgabeblack@google.com# the more exotic linker flags such as -Xlinker and -export-dynamic so
84712563Sgabeblack@google.com# we add them explicitly below. If you want to link in an alternate
8489651SAndreas.Sandberg@ARM.com# version of python, see above for instructions on how to invoke
84912056Sgabeblack@google.com# scons with the appropriate PATH set.
85012056Sgabeblack@google.compy_includes = readCommand(['python-config', '--includes'],
85112056Sgabeblack@google.com                          exception='').split()
85212563Sgabeblack@google.com# Strip the -I from the include folders before adding them to the
85312056Sgabeblack@google.com# CPPPATH
85410841Sandreas.sandberg@arm.commain.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
85510841Sandreas.sandberg@arm.com
85610841Sandreas.sandberg@arm.com# Read the linker flags and split them into libraries and other link
85710841Sandreas.sandberg@arm.com# flags. The libraries are added later through the call the CheckLib.
85810841Sandreas.sandberg@arm.compy_ld_flags = readCommand(['python-config', '--ldflags'], exception='').split()
85910841Sandreas.sandberg@arm.compy_libs = []
8609651SAndreas.Sandberg@ARM.comfor lib in py_ld_flags:
8619651SAndreas.Sandberg@ARM.com     if not lib.startswith('-l'):
8629651SAndreas.Sandberg@ARM.com         main.Append(LINKFLAGS=[lib])
8639651SAndreas.Sandberg@ARM.com     else:
8649651SAndreas.Sandberg@ARM.com         lib = lib[2:]
8659651SAndreas.Sandberg@ARM.com         if lib not in py_libs:
86612563Sgabeblack@google.com             py_libs.append(lib)
8679651SAndreas.Sandberg@ARM.com
8689651SAndreas.Sandberg@ARM.com# verify that this stuff works
86910841Sandreas.sandberg@arm.comif not conf.CheckHeader('Python.h', '<>'):
87012563Sgabeblack@google.com    print "Error: can't find Python.h header in", py_includes
87112563Sgabeblack@google.com    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
87210841Sandreas.sandberg@arm.com    Exit(1)
87310841Sandreas.sandberg@arm.com
87410841Sandreas.sandberg@arm.comfor lib in py_libs:
87510860Sandreas.sandberg@arm.com    if not conf.CheckLib(lib):
87610841Sandreas.sandberg@arm.com        print "Error: can't find library %s required by python" % lib
87710841Sandreas.sandberg@arm.com        Exit(1)
87810841Sandreas.sandberg@arm.com
87910841Sandreas.sandberg@arm.com# On Solaris you need to use libsocket for socket ops
88010841Sandreas.sandberg@arm.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
88112563Sgabeblack@google.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
88210841Sandreas.sandberg@arm.com       print "Can't find library with socket calls (e.g. accept())"
88310841Sandreas.sandberg@arm.com       Exit(1)
88410841Sandreas.sandberg@arm.com
88510841Sandreas.sandberg@arm.com# Check for zlib.  If the check passes, libz will be automatically
88610841Sandreas.sandberg@arm.com# added to the LIBS environment variable.
8879651SAndreas.Sandberg@ARM.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
8889651SAndreas.Sandberg@ARM.com    print 'Error: did not find needed zlib compression library '\
8899986Sandreas@sandberg.pp.se          'and/or zlib.h header file.'
8909986Sandreas@sandberg.pp.se    print '       Please install zlib and try again.'
8919986Sandreas@sandberg.pp.se    Exit(1)
8929986Sandreas@sandberg.pp.se
8939986Sandreas@sandberg.pp.se# If we have the protobuf compiler, also make sure we have the
8949986Sandreas@sandberg.pp.se# development libraries. If the check passes, libprotobuf will be
8955863Snate@binkert.org# automatically added to the LIBS environment variable. After
8965863Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
8975863Snate@binkert.org# got both protoc and libprotobuf available.
8985863Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
8996121Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9001858SN/A                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9015863Snate@binkert.org
9025863Snate@binkert.org# If we have the compiler but not the library, print another warning.
9035863Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9045863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9055863Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' + \
9062139SN/A    '       Please install libprotobuf-dev for tracing support.' + \
9074202Sbinkertn@umich.edu    termcap.Normal
90811308Santhony.gutierrez@amd.com
9094202Sbinkertn@umich.edu# Check for librt.
91011308Santhony.gutierrez@amd.comhave_posix_clock = \
9112139SN/A    conf.CheckLibWithHeader(None, 'time.h', 'C',
9126994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
9136994Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9146994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
9156994Snate@binkert.org
9166994Snate@binkert.orghave_posix_timers = \
9176994Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
9186994Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
9196994Snate@binkert.org
92010319SAndreas.Sandberg@ARM.comif conf.CheckLib('tcmalloc'):
9216994Snate@binkert.org    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9226994Snate@binkert.orgelif conf.CheckLib('tcmalloc_minimal'):
9236994Snate@binkert.org    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9246994Snate@binkert.orgelse:
9256994Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9266994Snate@binkert.org          "You can get a 12% performance improvement by installing tcmalloc "\
9276994Snate@binkert.org          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
9286994Snate@binkert.org          termcap.Normal
9296994Snate@binkert.org
9306994Snate@binkert.orgif not have_posix_clock:
9316994Snate@binkert.org    print "Can't find library for POSIX clocks."
9322155SN/A
9335863Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
9341869SN/Ahave_fenv = conf.CheckHeader('fenv.h', '<>')
9351869SN/Aif not have_fenv:
9365863Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
9375863Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
9384202Sbinkertn@umich.edu
9396108Snate@binkert.org# Check if we should enable KVM-based hardware virtualization
9406108Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
9416108Snate@binkert.orgif not have_kvm:
9426108Snate@binkert.org    print "Info: Header file <linux/kvm.h> not found, " \
9439219Spower.jg@gmail.com        "disabling KVM support."
9449219Spower.jg@gmail.com
9459219Spower.jg@gmail.com# Check if the requested target ISA is compatible with the host
9469219Spower.jg@gmail.comdef is_isa_kvm_compatible(isa):
9479219Spower.jg@gmail.com    isa_comp_table = {
9489219Spower.jg@gmail.com        "arm" : ( "armv7l" ),
9499219Spower.jg@gmail.com        "x86" : ( "x86_64" ),
9509219Spower.jg@gmail.com        }
9514202Sbinkertn@umich.edu    try:
9525863Snate@binkert.org        import platform
95310135SCurtis.Dunham@arm.com        host_isa = platform.machine()
95412563Sgabeblack@google.com    except:
9555742Snate@binkert.org        print "Warning: Failed to determine host ISA."
9568268Ssteve.reinhardt@amd.com        return False
95712563Sgabeblack@google.com
9588268Ssteve.reinhardt@amd.com    return host_isa in isa_comp_table.get(isa, [])
9595742Snate@binkert.org
9605341Sstever@gmail.com
9618474Sgblack@eecs.umich.edu######################################################################
96212563Sgabeblack@google.com#
9635342Sstever@gmail.com# Finish the configuration
9644202Sbinkertn@umich.edu#
9654202Sbinkertn@umich.edumain = conf.Finish()
96611308Santhony.gutierrez@amd.com
9674202Sbinkertn@umich.edu######################################################################
9685863Snate@binkert.org#
9695863Snate@binkert.org# Collect all non-global variables
97011308Santhony.gutierrez@amd.com#
9716994Snate@binkert.org
9726994Snate@binkert.org# Define the universe of supported ISAs
97310319SAndreas.Sandberg@ARM.comall_isa_list = [ ]
9745863Snate@binkert.orgExport('all_isa_list')
9755863Snate@binkert.org
9765863Snate@binkert.orgclass CpuModel(object):
9775863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9785863Snate@binkert.org    know about a particular CPU model.'''
9795863Snate@binkert.org
9805863Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9815863Snate@binkert.org    dict = {}
9827840Snate@binkert.org    list = []
9835863Snate@binkert.org    defaults = []
98412230Sgiacomo.travaglini@arm.com
98512230Sgiacomo.travaglini@arm.com    # Constructor.  Automatically adds models to CpuModel.dict.
98612230Sgiacomo.travaglini@arm.com    def __init__(self, name, filename, includes, strings, default=False):
98712230Sgiacomo.travaglini@arm.com        self.name = name           # name of model
98812230Sgiacomo.travaglini@arm.com        self.filename = filename   # filename for output exec code
98912056Sgabeblack@google.com        self.includes = includes   # include files needed in exec file
99012056Sgabeblack@google.com        # The 'strings' dict holds all the per-CPU symbols we can
99112056Sgabeblack@google.com        # substitute into templates etc.
99211308Santhony.gutierrez@amd.com        self.strings = strings
9939219Spower.jg@gmail.com
9949219Spower.jg@gmail.com        # This cpu is enabled by default
99511235Sandreas.sandberg@arm.com        self.default = default
99611235Sandreas.sandberg@arm.com
9971869SN/A        # Add self to dict
9981858SN/A        if name in CpuModel.dict:
9995863Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
100011308Santhony.gutierrez@amd.com        CpuModel.dict[name] = self
100112061Sjason@lowepower.com        CpuModel.list.append(name)
100212920Sgabeblack@google.com
100312920Sgabeblack@google.comExport('CpuModel')
10041858SN/A
1005955SN/A# Sticky variables get saved in the variables file so they persist from
1006955SN/A# one invocation to the next (unless overridden, in which case the new
10071869SN/A# value becomes sticky).
10081869SN/Asticky_vars = Variables(args=ARGUMENTS)
10091869SN/AExport('sticky_vars')
10101869SN/A
10111869SN/A# Sticky variables that should be exported
10125863Snate@binkert.orgexport_vars = []
10135863Snate@binkert.orgExport('export_vars')
10145863Snate@binkert.org
10151869SN/A# For Ruby
10165863Snate@binkert.orgall_protocols = []
10171869SN/AExport('all_protocols')
101812563Sgabeblack@google.comprotocol_dirs = []
10191869SN/AExport('protocol_dirs')
10201869SN/Aslicc_includes = []
10211869SN/AExport('slicc_includes')
10221869SN/A
10238483Sgblack@eecs.umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
10241869SN/A# above variables
10251869SN/Aif not GetOption('verbose'):
10261869SN/A    print "Reading SConsopts"
10271869SN/Afor bdir in [ base_dir ] + extras_dir_list:
10285863Snate@binkert.org    if not isdir(bdir):
10295863Snate@binkert.org        print "Error: directory '%s' does not exist" % bdir
10301869SN/A        Exit(1)
10315863Snate@binkert.org    for root, dirs, files in os.walk(bdir):
10325863Snate@binkert.org        if 'SConsopts' in files:
10333356Sbinkertn@umich.edu            if GetOption('verbose'):
10343356Sbinkertn@umich.edu                print "Reading", joinpath(root, 'SConsopts')
10353356Sbinkertn@umich.edu            SConscript(joinpath(root, 'SConsopts'))
10363356Sbinkertn@umich.edu
10373356Sbinkertn@umich.eduall_isa_list.sort()
10384781Snate@binkert.org
10395863Snate@binkert.orgsticky_vars.AddVariables(
10405863Snate@binkert.org    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
10411869SN/A    ListVariable('CPU_MODELS', 'CPU models',
10421869SN/A                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
10431869SN/A                 sorted(CpuModel.list)),
10446121Snate@binkert.org    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
10451869SN/A                 False),
104611982Sgabeblack@google.com    BoolVariable('SS_COMPATIBLE_FP',
104711982Sgabeblack@google.com                 'Make floating-point results compatible with SimpleScalar',
104811982Sgabeblack@google.com                 False),
104911982Sgabeblack@google.com    BoolVariable('USE_SSE2',
105011982Sgabeblack@google.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
105111982Sgabeblack@google.com                 False),
105211982Sgabeblack@google.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
105311982Sgabeblack@google.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
105411982Sgabeblack@google.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
105511982Sgabeblack@google.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
105611982Sgabeblack@google.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
105711982Sgabeblack@google.com                  all_protocols),
105811982Sgabeblack@google.com    )
105911982Sgabeblack@google.com
106011982Sgabeblack@google.com# These variables get exported to #defines in config/*.hh (see src/SConscript).
106111982Sgabeblack@google.comexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
106211982Sgabeblack@google.com                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
106311982Sgabeblack@google.com
106411982Sgabeblack@google.com###################################################
106511982Sgabeblack@google.com#
106611982Sgabeblack@google.com# Define a SCons builder for configuration flag headers.
106711982Sgabeblack@google.com#
106811982Sgabeblack@google.com###################################################
106911982Sgabeblack@google.com
107011982Sgabeblack@google.com# This function generates a config header file that #defines the
107111982Sgabeblack@google.com# variable symbol to the current variable setting (0 or 1).  The source
107211978Sgabeblack@google.com# operands are the name of the variable and a Value node containing the
107311978Sgabeblack@google.com# value of the variable.
107412034Sgabeblack@google.comdef build_config_file(target, source, env):
107511978Sgabeblack@google.com    (variable, value) = [s.get_contents() for s in source]
107611978Sgabeblack@google.com    f = file(str(target[0]), 'w')
107711978Sgabeblack@google.com    print >> f, '#define', variable, value
107812034Sgabeblack@google.com    f.close()
107911978Sgabeblack@google.com    return None
108011978Sgabeblack@google.com
108110915Sandreas.sandberg@arm.com# Combine the two functions into a scons Action object.
108211986Sandreas.sandberg@arm.comconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
108311986Sandreas.sandberg@arm.com
10841869SN/A# The emitter munges the source & target node lists to reflect what
10851869SN/A# we're really doing.
108612015Sgabeblack@google.comdef config_emitter(target, source, env):
108712015Sgabeblack@google.com    # extract variable name from Builder arg
108812015Sgabeblack@google.com    variable = str(target[0])
108912015Sgabeblack@google.com    # True target is config header file
10903546Sgblack@eecs.umich.edu    target = joinpath('config', variable.lower() + '.hh')
10913546Sgblack@eecs.umich.edu    val = env[variable]
10923546Sgblack@eecs.umich.edu    if isinstance(val, bool):
109312015Sgabeblack@google.com        # Force value to 0/1
109412015Sgabeblack@google.com        val = int(val)
109512015Sgabeblack@google.com    elif isinstance(val, str):
109612015Sgabeblack@google.com        val = '"' + val + '"'
109712015Sgabeblack@google.com
109812015Sgabeblack@google.com    # Sources are variable name & value (packaged in SCons Value nodes)
109912015Sgabeblack@google.com    return ([target], [Value(variable), Value(val)])
110012563Sgabeblack@google.com
11013546Sgblack@eecs.umich.educonfig_builder = Builder(emitter = config_emitter, action = config_action)
110212015Sgabeblack@google.com
110312015Sgabeblack@google.commain.Append(BUILDERS = { 'ConfigFile' : config_builder })
110410196SCurtis.Dunham@arm.com
110512015Sgabeblack@google.com# libelf build is shared across all configs in the build root.
110612015Sgabeblack@google.commain.SConscript('ext/libelf/SConscript',
110712015Sgabeblack@google.com                variant_dir = joinpath(build_root, 'libelf'))
110812015Sgabeblack@google.com
110912015Sgabeblack@google.com# gzstream build is shared across all configs in the build root.
111012015Sgabeblack@google.commain.SConscript('ext/gzstream/SConscript',
111112015Sgabeblack@google.com                variant_dir = joinpath(build_root, 'gzstream'))
111212015Sgabeblack@google.com
111312015Sgabeblack@google.com# libfdt build is shared across all configs in the build root.
111412015Sgabeblack@google.commain.SConscript('ext/libfdt/SConscript',
111512015Sgabeblack@google.com                variant_dir = joinpath(build_root, 'libfdt'))
11163546Sgblack@eecs.umich.edu
11173546Sgblack@eecs.umich.edu# fputils build is shared across all configs in the build root.
11183546Sgblack@eecs.umich.edumain.SConscript('ext/fputils/SConscript',
1119955SN/A                variant_dir = joinpath(build_root, 'fputils'))
1120955SN/A
1121955SN/A###################################################
1122955SN/A#
11235863Snate@binkert.org# This function is used to set up a directory with switching headers
112410135SCurtis.Dunham@arm.com#
112512563Sgabeblack@google.com###################################################
11265343Sstever@gmail.com
11275343Sstever@gmail.commain['ALL_ISA_LIST'] = all_isa_list
11286121Snate@binkert.orgdef make_switching_dir(dname, switch_headers, env):
11295863Snate@binkert.org    # Generate the header.  target[0] is the full path of the output
11304773Snate@binkert.org    # header to generate.  'source' is a dummy variable, since we get the
11315863Snate@binkert.org    # list of ISAs from env['ALL_ISA_LIST'].
11322632Sstever@eecs.umich.edu    def gen_switch_hdr(target, source, env):
11335863Snate@binkert.org        fname = str(target[0])
11342023SN/A        f = open(fname, 'w')
11355863Snate@binkert.org        isa = env['TARGET_ISA'].lower()
11365863Snate@binkert.org        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
11375863Snate@binkert.org        f.close()
11385863Snate@binkert.org
11395863Snate@binkert.org    # Build SCons Action object. 'varlist' specifies env vars that this
11405863Snate@binkert.org    # action depends on; when env['ALL_ISA_LIST'] changes these actions
11415863Snate@binkert.org    # should get re-executed.
11425863Snate@binkert.org    switch_hdr_action = MakeAction(gen_switch_hdr,
114310135SCurtis.Dunham@arm.com                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
114412563Sgabeblack@google.com
114512034Sgabeblack@google.com    # Instantiate actions for each header
114612034Sgabeblack@google.com    for hdr in switch_headers:
114712034Sgabeblack@google.com        env.Command(hdr, [], switch_hdr_action)
11482632Sstever@eecs.umich.eduExport('make_switching_dir')
11495863Snate@binkert.org
11502023SN/A###################################################
11512632Sstever@eecs.umich.edu#
11525863Snate@binkert.org# Define build environments for selected configurations.
11535342Sstever@gmail.com#
11545863Snate@binkert.org###################################################
11552632Sstever@eecs.umich.edu
11565863Snate@binkert.orgfor variant_path in variant_paths:
11575863Snate@binkert.org    print "Building in", variant_path
11588267Ssteve.reinhardt@amd.com
11598120Sgblack@eecs.umich.edu    # Make a copy of the build-root environment to use for this config.
11608267Ssteve.reinhardt@amd.com    env = main.Clone()
11618267Ssteve.reinhardt@amd.com    env['BUILDDIR'] = variant_path
11628267Ssteve.reinhardt@amd.com
11638267Ssteve.reinhardt@amd.com    # variant_dir is the tail component of build path, and is used to
11648267Ssteve.reinhardt@amd.com    # determine the build parameters (e.g., 'ALPHA_SE')
11658267Ssteve.reinhardt@amd.com    (build_root, variant_dir) = splitpath(variant_path)
11668267Ssteve.reinhardt@amd.com
11678267Ssteve.reinhardt@amd.com    # Set env variables according to the build directory config.
11688267Ssteve.reinhardt@amd.com    sticky_vars.files = []
11695863Snate@binkert.org    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
117012563Sgabeblack@google.com    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
117112563Sgabeblack@google.com    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
11722632Sstever@eecs.umich.edu    current_vars_file = joinpath(build_root, 'variables', variant_dir)
117312563Sgabeblack@google.com    if isfile(current_vars_file):
117412563Sgabeblack@google.com        sticky_vars.files.append(current_vars_file)
117512563Sgabeblack@google.com        print "Using saved variables file %s" % current_vars_file
11762632Sstever@eecs.umich.edu    else:
11771888SN/A        # Build dir-specific variables file doesn't exist.
11785863Snate@binkert.org
11795863Snate@binkert.org        # Make sure the directory is there so we can create it later
11801858SN/A        opt_dir = dirname(current_vars_file)
11818120Sgblack@eecs.umich.edu        if not isdir(opt_dir):
11828120Sgblack@eecs.umich.edu            mkdir(opt_dir)
11837756SAli.Saidi@ARM.com
11842598SN/A        # Get default build variables from source tree.  Variables are
11855863Snate@binkert.org        # normally determined by name of $VARIANT_DIR, but can be
11861858SN/A        # overridden by '--default=' arg on command line.
11871858SN/A        default = GetOption('default')
118812563Sgabeblack@google.com        opts_dir = joinpath(main.root.abspath, 'build_opts')
118912563Sgabeblack@google.com        if default:
11901858SN/A            default_vars_files = [joinpath(build_root, 'variables', default),
11911858SN/A                                  joinpath(opts_dir, default)]
11921858SN/A        else:
119312563Sgabeblack@google.com            default_vars_files = [joinpath(opts_dir, variant_dir)]
119412563Sgabeblack@google.com        existing_files = filter(isfile, default_vars_files)
119512563Sgabeblack@google.com        if existing_files:
11961858SN/A            default_vars_file = existing_files[0]
119712230Sgiacomo.travaglini@arm.com            sticky_vars.files.append(default_vars_file)
119812563Sgabeblack@google.com            print "Variables file %s not found,\n  using defaults in %s" \
119912563Sgabeblack@google.com                  % (current_vars_file, default_vars_file)
120012230Sgiacomo.travaglini@arm.com        else:
120112230Sgiacomo.travaglini@arm.com            print "Error: cannot find variables file %s or " \
120212230Sgiacomo.travaglini@arm.com                  "default file(s) %s" \
120312230Sgiacomo.travaglini@arm.com                  % (current_vars_file, ' or '.join(default_vars_files))
120412230Sgiacomo.travaglini@arm.com            Exit(1)
12051858SN/A
12061858SN/A    # Apply current variable settings to env
12071858SN/A    sticky_vars.Update(env)
12089651SAndreas.Sandberg@ARM.com
12099651SAndreas.Sandberg@ARM.com    help_texts["local_vars"] += \
121012563Sgabeblack@google.com        "Build variables for %s:\n" % variant_dir \
121112563Sgabeblack@google.com                 + sticky_vars.GenerateHelpText(env)
12129651SAndreas.Sandberg@ARM.com
12139651SAndreas.Sandberg@ARM.com    # Process variable settings.
121412563Sgabeblack@google.com
121512563Sgabeblack@google.com    if not have_fenv and env['USE_FENV']:
12169651SAndreas.Sandberg@ARM.com        print "Warning: <fenv.h> not available; " \
12179651SAndreas.Sandberg@ARM.com              "forcing USE_FENV to False in", variant_dir + "."
121812056Sgabeblack@google.com        env['USE_FENV'] = False
121912056Sgabeblack@google.com
122012563Sgabeblack@google.com    if not env['USE_FENV']:
122112056Sgabeblack@google.com        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
122212056Sgabeblack@google.com        print "         FP results may deviate slightly from other platforms."
122311798Santhony.gutierrez@amd.com
122411798Santhony.gutierrez@amd.com    if env['EFENCE']:
122511798Santhony.gutierrez@amd.com        env.Append(LIBS=['efence'])
12269986Sandreas@sandberg.pp.se
12279986Sandreas@sandberg.pp.se    if env['USE_KVM']:
12289986Sandreas@sandberg.pp.se        if not have_kvm:
122912563Sgabeblack@google.com            print "Warning: Can not enable KVM, host seems to lack KVM support"
123012563Sgabeblack@google.com            env['USE_KVM'] = False
123112563Sgabeblack@google.com        elif not have_posix_timers:
12329986Sandreas@sandberg.pp.se            print "Warning: Can not enable KVM, host seems to lack support " \
12335863Snate@binkert.org                "for POSIX timers"
12345863Snate@binkert.org            env['USE_KVM'] = False
12351869SN/A        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
12361965SN/A            print "Info: KVM support disabled due to unsupported host and " \
12377739Sgblack@eecs.umich.edu                "target ISA combination"
12381965SN/A            env['USE_KVM'] = False
12392761Sstever@eecs.umich.edu
12405863Snate@binkert.org    # Save sticky variable settings back to current variables file
12411869SN/A    sticky_vars.Save(current_vars_file, env)
124210196SCurtis.Dunham@arm.com
12431869SN/A    if env['USE_SSE2']:
12448120Sgblack@eecs.umich.edu        env.Append(CCFLAGS=['-msse2'])
12458120Sgblack@eecs.umich.edu
12468120Sgblack@eecs.umich.edu    # The src/SConscript file sets up the build rules in 'env' according
12478120Sgblack@eecs.umich.edu    # to the configured variables.  It returns a list of environments,
12488120Sgblack@eecs.umich.edu    # one for each variant build (debug, opt, etc.)
12498120Sgblack@eecs.umich.edu    envList = SConscript('src/SConscript', variant_dir = variant_path,
12508120Sgblack@eecs.umich.edu                         exports = 'env')
12518120Sgblack@eecs.umich.edu
12528120Sgblack@eecs.umich.edu    # Set up the regression tests for each build.
12538120Sgblack@eecs.umich.edu    for e in envList:
12548120Sgblack@eecs.umich.edu        SConscript('tests/SConscript',
12558120Sgblack@eecs.umich.edu                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1256                   exports = { 'env' : e }, duplicate = False)
1257
1258# base help text
1259Help('''
1260Usage: scons [scons options] [build variables] [target(s)]
1261
1262Extra scons options:
1263%(options)s
1264
1265Global build variables:
1266%(global_vars)s
1267
1268%(local_vars)s
1269''' % help_texts)
1270