SConstruct revision 9926
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013 ARM Limited
45871Snate@binkert.org# All rights reserved.
51762SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
312665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
325863Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
392632Sstever@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42955SN/A#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452761Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522632Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562761Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582761Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
642632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
652632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
68955SN/A#   in a directory outside of the source tree.  The '-C' option tells
695863Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705863Snate@binkert.org#   file.
715863Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725863Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735863Snate@binkert.org#
745863Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
755863Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
765863Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
775863Snate@binkert.org# options as well.
785863Snate@binkert.org#
795863Snate@binkert.org###################################################
805863Snate@binkert.org
815863Snate@binkert.org# Check for recent-enough Python and SCons versions.
825863Snate@binkert.orgtry:
835863Snate@binkert.org    # Really old versions of scons only take two options for the
845863Snate@binkert.org    # function, so check once without the revision and once with the
855863Snate@binkert.org    # revision, the first instance will fail for stuff other than
865863Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
875863Snate@binkert.org    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
905863Snate@binkert.org    print """
915863Snate@binkert.orgFor more details, see:
925863Snate@binkert.org    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
955863Snate@binkert.org
965863Snate@binkert.org# We ensure the python version early because because python-config
975863Snate@binkert.org# requires python 2.5
985863Snate@binkert.orgtry:
995863Snate@binkert.org    EnsurePythonVersion(2, 5)
1006654Snate@binkert.orgexcept SystemExit, e:
101955SN/A    print """
1025396Ssaidi@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1035863Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1045863Snate@binkert.org'python-config' first.
1054202Sbinkertn@umich.edu
1065863Snate@binkert.orgFor more details, see:
1075863Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1085863Snate@binkert.org"""
1095863Snate@binkert.org    raise
110955SN/A
1116654Snate@binkert.org# Global Python includes
1125273Sstever@gmail.comimport os
1135871Snate@binkert.orgimport re
1145273Sstever@gmail.comimport subprocess
1156655Snate@binkert.orgimport sys
1166655Snate@binkert.org
1176655Snate@binkert.orgfrom os import mkdir, environ
1186655Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1196655Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1206655Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1215871Snate@binkert.org
1226654Snate@binkert.org# SCons includes
1235396Ssaidi@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 = {
1378120Sgblack@eecs.umich.edu    "options" : "",
1388120Sgblack@eecs.umich.edu    "global_vars" : "",
1398120Sgblack@eecs.umich.edu    "local_vars" : ""
1408120Sgblack@eecs.umich.edu}
1418120Sgblack@eecs.umich.edu
1428120Sgblack@eecs.umich.eduExport("help_texts")
1438120Sgblack@eecs.umich.edu
1448120Sgblack@eecs.umich.edu
1458120Sgblack@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1468120Sgblack@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1478120Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1488120Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1498120Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1508120Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1518120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1528120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1538120Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1548120Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1558120Sgblack@eecs.umich.edu# we can just use AddOption directly.
1568120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1578120Sgblack@eecs.umich.edu    col_width = 30
1588120Sgblack@eecs.umich.edu
1598120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1607816Ssteve.reinhardt@amd.com    if "help" in kwargs:
1617816Ssteve.reinhardt@amd.com        length = len(help)
1627816Ssteve.reinhardt@amd.com        if length >= col_width:
1637816Ssteve.reinhardt@amd.com            help += "\n" + " " * col_width
1647816Ssteve.reinhardt@amd.com        else:
1657816Ssteve.reinhardt@amd.com            help += " " * (col_width - length)
1667816Ssteve.reinhardt@amd.com        help += kwargs["help"]
1677816Ssteve.reinhardt@amd.com    help_texts["options"] += help + "\n"
1687816Ssteve.reinhardt@amd.com
1695871Snate@binkert.org    AddOption(*args, **kwargs)
1705871Snate@binkert.org
1716121Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1725871Snate@binkert.org               help="Add color to abbreviated scons output")
1735871Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1746003Snate@binkert.org               help="Don't add color to abbreviated scons output")
1756655Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
176955SN/A               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')
1795871Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1805871Snate@binkert.org               help='Disable Link-Time Optimization for fast')
181955SN/AAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1826121Snate@binkert.org               help='Update test reference outputs')
1836121Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1846121Snate@binkert.org               help='Print full tool command lines')
1851533SN/A
1866655Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1876655Snate@binkert.org
1886655Snate@binkert.org########################################################################
1896655Snate@binkert.org#
1905871Snate@binkert.org# Set up the main build environment.
1915871Snate@binkert.org#
1925863Snate@binkert.org########################################################################
1935871Snate@binkert.org
1945871Snate@binkert.org# export TERM so that clang reports errors in color
1955871Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1965871Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1975871Snate@binkert.org                 'RANLIB', 'SWIG', 'TERM' ])
1985863Snate@binkert.org
1996121Snate@binkert.orguse_prefixes = [
2005863Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
2015871Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2028336Ssteve.reinhardt@amd.com    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2038336Ssteve.reinhardt@amd.com    "CCC_",         # clang static analyzer configuration
2048336Ssteve.reinhardt@amd.com    ]
2058336Ssteve.reinhardt@amd.com
2064678Snate@binkert.orguse_env = {}
2078336Ssteve.reinhardt@amd.comfor key,val in os.environ.iteritems():
2088336Ssteve.reinhardt@amd.com    if key in use_vars or \
2098336Ssteve.reinhardt@amd.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2104678Snate@binkert.org        use_env[key] = val
2114678Snate@binkert.org
2124678Snate@binkert.orgmain = Environment(ENV=use_env)
2134678Snate@binkert.orgmain.Decider('MD5-timestamp')
2147827Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
2157827Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
2168336Ssteve.reinhardt@amd.com
2174678Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2188336Ssteve.reinhardt@amd.com
2198336Ssteve.reinhardt@amd.com# Check that we have a C/C++ compiler
2208336Ssteve.reinhardt@amd.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2218336Ssteve.reinhardt@amd.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2228336Ssteve.reinhardt@amd.com    Exit(1)
2238336Ssteve.reinhardt@amd.com
2245871Snate@binkert.org# Check that swig is present
2255871Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2268336Ssteve.reinhardt@amd.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
2278336Ssteve.reinhardt@amd.com    Exit(1)
2288336Ssteve.reinhardt@amd.com
2298336Ssteve.reinhardt@amd.com# add useful python code PYTHONPATH so it can be used by subprocesses
2308336Ssteve.reinhardt@amd.com# as well
2315871Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2328336Ssteve.reinhardt@amd.com
2338336Ssteve.reinhardt@amd.com########################################################################
2348336Ssteve.reinhardt@amd.com#
2358336Ssteve.reinhardt@amd.com# Mercurial Stuff.
2368336Ssteve.reinhardt@amd.com#
2374678Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2385871Snate@binkert.org# extra things.
2394678Snate@binkert.org#
2408336Ssteve.reinhardt@amd.com########################################################################
2418336Ssteve.reinhardt@amd.com
2428336Ssteve.reinhardt@amd.comhgdir = main.root.Dir(".hg")
2438336Ssteve.reinhardt@amd.com
2448336Ssteve.reinhardt@amd.commercurial_style_message = """
2458336Ssteve.reinhardt@amd.comYou're missing the gem5 style hook, which automatically checks your code
2468336Ssteve.reinhardt@amd.comagainst the gem5 style rules on hg commit and qrefresh commands.  This
2478336Ssteve.reinhardt@amd.comscript will now install the hook in your .hg/hgrc file.
2488336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2498336Ssteve.reinhardt@amd.com
2508336Ssteve.reinhardt@amd.commercurial_style_hook = """
2518336Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2528336Ssteve.reinhardt@amd.com# to provide the gem5 style-checking hooks
2538336Ssteve.reinhardt@amd.com[extensions]
2548336Ssteve.reinhardt@amd.comstyle = %s/util/style.py
2558336Ssteve.reinhardt@amd.com
2568336Ssteve.reinhardt@amd.com[hooks]
2575871Snate@binkert.orgpretxncommit.style = python:style.check_style
2586121Snate@binkert.orgpre-qrefresh.style = python:style.check_style
259955SN/A# End of SConstruct additions
260955SN/A
2612632Sstever@eecs.umich.edu""" % (main.root.abspath)
2622632Sstever@eecs.umich.edu
263955SN/Amercurial_lib_not_found = """
264955SN/AMercurial libraries cannot be found, ignoring style hook.  If
265955SN/Ayou are a gem5 developer, please fix this and run the style
266955SN/Ahook. It is important.
2675863Snate@binkert.org"""
268955SN/A
2692632Sstever@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
2702632Sstever@eecs.umich.edu# Skip this if --ignore-style was specified, there's no .hg dir to
2712632Sstever@eecs.umich.edu# install a hook in, or there's no interactive terminal to prompt.
2722632Sstever@eecs.umich.eduif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2732632Sstever@eecs.umich.edu    style_hook = True
2742632Sstever@eecs.umich.edu    try:
2752632Sstever@eecs.umich.edu        from mercurial import ui
2768268Ssteve.reinhardt@amd.com        ui = ui.ui()
2778268Ssteve.reinhardt@amd.com        ui.readconfig(hgdir.File('hgrc').abspath)
2788268Ssteve.reinhardt@amd.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2798268Ssteve.reinhardt@amd.com                     ui.config('hooks', 'pre-qrefresh.style', None)
2808268Ssteve.reinhardt@amd.com    except ImportError:
2818268Ssteve.reinhardt@amd.com        print mercurial_lib_not_found
2828268Ssteve.reinhardt@amd.com
2832632Sstever@eecs.umich.edu    if not style_hook:
2842632Sstever@eecs.umich.edu        print mercurial_style_message,
2852632Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
2862632Sstever@eecs.umich.edu        try:
2878268Ssteve.reinhardt@amd.com            raw_input()
2882632Sstever@eecs.umich.edu        except:
2898268Ssteve.reinhardt@amd.com            print "Input exception, exiting scons.\n"
2908268Ssteve.reinhardt@amd.com            sys.exit(1)
2918268Ssteve.reinhardt@amd.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2928268Ssteve.reinhardt@amd.com        print "Adding style hook to", hgrc_path, "\n"
2933718Sstever@eecs.umich.edu        try:
2942634Sstever@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
2952634Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
2965863Snate@binkert.org            hgrc.close()
2972638Sstever@eecs.umich.edu        except:
2988268Ssteve.reinhardt@amd.com            print "Error updating", hgrc_path
2992632Sstever@eecs.umich.edu            sys.exit(1)
3002632Sstever@eecs.umich.edu
3012632Sstever@eecs.umich.edu
3022632Sstever@eecs.umich.edu###################################################
3032632Sstever@eecs.umich.edu#
3041858SN/A# Figure out which configurations to set up based on the path(s) of
3053716Sstever@eecs.umich.edu# the target(s).
3062638Sstever@eecs.umich.edu#
3072638Sstever@eecs.umich.edu###################################################
3082638Sstever@eecs.umich.edu
3092638Sstever@eecs.umich.edu# Find default configuration & binary.
3102638Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3112638Sstever@eecs.umich.edu
3122638Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
3135863Snate@binkert.orgdef rfind(l, elt, offs = -1):
3145863Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
3155863Snate@binkert.org        if l[i] == elt:
316955SN/A            return i
3175341Sstever@gmail.com    raise ValueError, "element not found"
3185341Sstever@gmail.com
3195863Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
3207756SAli.Saidi@ARM.com# paths made absolute and ~-expanded.  Paths will be interpreted
3215341Sstever@gmail.com# relative to the launch directory unless a different root is provided
3226121Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3234494Ssaidi@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
3246121Snate@binkert.org            for p in path_list]
3251105SN/A
3262667Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
3272667Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
3282667Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3292667Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3306121Snate@binkert.org# follow 'build' in the build path.
3312667Sstever@eecs.umich.edu
3325341Sstever@gmail.com# The funky assignment to "[:]" is needed to replace the list contents
3335863Snate@binkert.org# in place rather than reassign the symbol to a new list, which
3345341Sstever@gmail.com# doesn't work (obviously!).
3355341Sstever@gmail.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3365341Sstever@gmail.com
3378120Sgblack@eecs.umich.edu# Generate a list of the unique build roots and configs that the
3385341Sstever@gmail.com# collected targets reference.
3398120Sgblack@eecs.umich.eduvariant_paths = []
3405341Sstever@gmail.combuild_root = None
3418120Sgblack@eecs.umich.edufor t in BUILD_TARGETS:
3426121Snate@binkert.org    path_dirs = t.split('/')
3436121Snate@binkert.org    try:
3445397Ssaidi@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3455397Ssaidi@eecs.umich.edu    except:
3467727SAli.Saidi@ARM.com        print "Error: no non-leaf 'build' dir found on target path", t
3478268Ssteve.reinhardt@amd.com        Exit(1)
3486168Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3495341Sstever@gmail.com    if not build_root:
3508120Sgblack@eecs.umich.edu        build_root = this_build_root
3518120Sgblack@eecs.umich.edu    else:
3528120Sgblack@eecs.umich.edu        if this_build_root != build_root:
3536814Sgblack@eecs.umich.edu            print "Error: build targets not under same build root\n"\
3545863Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3558120Sgblack@eecs.umich.edu            Exit(1)
3565341Sstever@gmail.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
3575863Snate@binkert.org    if variant_path not in variant_paths:
3588268Ssteve.reinhardt@amd.com        variant_paths.append(variant_path)
3596121Snate@binkert.org
3606121Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
3618268Ssteve.reinhardt@amd.comif not isdir(build_root):
3625742Snate@binkert.org    mkdir(build_root)
3635742Snate@binkert.orgmain['BUILDROOT'] = build_root
3645341Sstever@gmail.com
3655742Snate@binkert.orgExport('main')
3665742Snate@binkert.org
3675341Sstever@gmail.commain.SConsignFile(joinpath(build_root, "sconsign"))
3686017Snate@binkert.org
3696121Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3706017Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
3717816Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
3727756SAli.Saidi@ARM.com# (soft) links work better.
3737756SAli.Saidi@ARM.commain.SetOption('duplicate', 'soft-copy')
3747756SAli.Saidi@ARM.com
3757756SAli.Saidi@ARM.com#
3767756SAli.Saidi@ARM.com# Set up global sticky variables... these are common to an entire build
3777756SAli.Saidi@ARM.com# tree (not specific to a particular build like ALPHA_SE)
3787756SAli.Saidi@ARM.com#
3797756SAli.Saidi@ARM.com
3807816Ssteve.reinhardt@amd.comglobal_vars_file = joinpath(build_root, 'variables.global')
3817816Ssteve.reinhardt@amd.com
3827816Ssteve.reinhardt@amd.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3837816Ssteve.reinhardt@amd.com
3847816Ssteve.reinhardt@amd.comglobal_vars.AddVariables(
3857816Ssteve.reinhardt@amd.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3867816Ssteve.reinhardt@amd.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3877816Ssteve.reinhardt@amd.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3887816Ssteve.reinhardt@amd.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3897816Ssteve.reinhardt@amd.com    ('BATCH', 'Use batch pool for build and tests', False),
3907756SAli.Saidi@ARM.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3917816Ssteve.reinhardt@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3927816Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
3937816Ssteve.reinhardt@amd.com    )
3947816Ssteve.reinhardt@amd.com
3957816Ssteve.reinhardt@amd.com# Update main environment with values from ARGUMENTS & global_vars_file
3967816Ssteve.reinhardt@amd.comglobal_vars.Update(main)
3977816Ssteve.reinhardt@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3987816Ssteve.reinhardt@amd.com
3997816Ssteve.reinhardt@amd.com# Save sticky variable settings back to current variables file
4007816Ssteve.reinhardt@amd.comglobal_vars.Save(global_vars_file, main)
4017816Ssteve.reinhardt@amd.com
4027816Ssteve.reinhardt@amd.com# Parse EXTRAS variable to build list of all directories where we're
4037816Ssteve.reinhardt@amd.com# look for sources etc.  This list is exported as extras_dir_list.
4047816Ssteve.reinhardt@amd.combase_dir = main.srcdir.abspath
4057816Ssteve.reinhardt@amd.comif main['EXTRAS']:
4067816Ssteve.reinhardt@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4077816Ssteve.reinhardt@amd.comelse:
4087816Ssteve.reinhardt@amd.com    extras_dir_list = []
4097816Ssteve.reinhardt@amd.com
4107816Ssteve.reinhardt@amd.comExport('base_dir')
4117816Ssteve.reinhardt@amd.comExport('extras_dir_list')
4127816Ssteve.reinhardt@amd.com
4137816Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
4147816Ssteve.reinhardt@amd.commain.Append(CPPPATH=[Dir('ext')])
4157816Ssteve.reinhardt@amd.com
4167816Ssteve.reinhardt@amd.comdef strip_build_path(path, env):
4177816Ssteve.reinhardt@amd.com    path = str(path)
4187816Ssteve.reinhardt@amd.com    variant_base = env['BUILDROOT'] + os.path.sep
4197816Ssteve.reinhardt@amd.com    if path.startswith(variant_base):
4207816Ssteve.reinhardt@amd.com        path = path[len(variant_base):]
4217816Ssteve.reinhardt@amd.com    elif path.startswith('build/'):
4227816Ssteve.reinhardt@amd.com        path = path[6:]
4237816Ssteve.reinhardt@amd.com    return path
4247816Ssteve.reinhardt@amd.com
4257816Ssteve.reinhardt@amd.com# Generate a string of the form:
4267816Ssteve.reinhardt@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
4277816Ssteve.reinhardt@amd.com# to print while building.
4287816Ssteve.reinhardt@amd.comclass Transform(object):
4297816Ssteve.reinhardt@amd.com    # all specific color settings should be here and nowhere else
4307816Ssteve.reinhardt@amd.com    tool_color = termcap.Normal
4317816Ssteve.reinhardt@amd.com    pfx_color = termcap.Yellow
4327816Ssteve.reinhardt@amd.com    srcs_color = termcap.Yellow + termcap.Bold
4337816Ssteve.reinhardt@amd.com    arrow_color = termcap.Blue + termcap.Bold
4347816Ssteve.reinhardt@amd.com    tgts_color = termcap.Yellow + termcap.Bold
4357816Ssteve.reinhardt@amd.com
4367816Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
4377816Ssteve.reinhardt@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
4387816Ssteve.reinhardt@amd.com                      + self.pfx_color + "%s" \
4397816Ssteve.reinhardt@amd.com                      + self.srcs_color + "%s" \
4407816Ssteve.reinhardt@amd.com                      + self.arrow_color + " -> " \
4417816Ssteve.reinhardt@amd.com                      + self.tgts_color + "%s" \
4427816Ssteve.reinhardt@amd.com                      + termcap.Normal
4437816Ssteve.reinhardt@amd.com        self.max_sources = max_sources
4447816Ssteve.reinhardt@amd.com
4457816Ssteve.reinhardt@amd.com    def __call__(self, target, source, env, for_signature=None):
4467816Ssteve.reinhardt@amd.com        # truncate source list according to max_sources param
4477816Ssteve.reinhardt@amd.com        source = source[0:self.max_sources]
4487816Ssteve.reinhardt@amd.com        def strip(f):
4497816Ssteve.reinhardt@amd.com            return strip_build_path(str(f), env)
4507816Ssteve.reinhardt@amd.com        if len(source) > 0:
4517816Ssteve.reinhardt@amd.com            srcs = map(strip, source)
4527756SAli.Saidi@ARM.com        else:
4538120Sgblack@eecs.umich.edu            srcs = ['']
4547756SAli.Saidi@ARM.com        tgts = map(strip, target)
4557756SAli.Saidi@ARM.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4567756SAli.Saidi@ARM.com        # operation that has nothing to do with paths.
4577756SAli.Saidi@ARM.com        com_pfx = os.path.commonprefix(srcs + tgts)
4587816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4597816Ssteve.reinhardt@amd.com        if com_pfx:
4607816Ssteve.reinhardt@amd.com            # do some cleanup and sanity checking on common prefix
4617816Ssteve.reinhardt@amd.com            if com_pfx[-1] == ".":
4627816Ssteve.reinhardt@amd.com                # prefix matches all but file extension: ok
4637816Ssteve.reinhardt@amd.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4647816Ssteve.reinhardt@amd.com                com_pfx = com_pfx[0:-1]
4657816Ssteve.reinhardt@amd.com            elif com_pfx[-1] == "/":
4667816Ssteve.reinhardt@amd.com                # common prefix is directory path: OK
4677816Ssteve.reinhardt@amd.com                pass
4687756SAli.Saidi@ARM.com            else:
4697756SAli.Saidi@ARM.com                src0_len = len(srcs[0])
4706654Snate@binkert.org                tgt0_len = len(tgts[0])
4716654Snate@binkert.org                if src0_len == com_pfx_len:
4725871Snate@binkert.org                    # source is a substring of target, OK
4736121Snate@binkert.org                    pass
4746121Snate@binkert.org                elif tgt0_len == com_pfx_len:
4756121Snate@binkert.org                    # target is a substring of source, need to back up to
4766121Snate@binkert.org                    # avoid empty string on RHS of arrow
4773940Ssaidi@eecs.umich.edu                    sep_idx = com_pfx.rfind(".")
4783918Ssaidi@eecs.umich.edu                    if sep_idx != -1:
4793918Ssaidi@eecs.umich.edu                        com_pfx = com_pfx[0:sep_idx]
4801858SN/A                    else:
4816121Snate@binkert.org                        com_pfx = ''
4827739Sgblack@eecs.umich.edu                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4837739Sgblack@eecs.umich.edu                    # still splitting at file extension: ok
4846143Snate@binkert.org                    pass
4857739Sgblack@eecs.umich.edu                else:
4867618SAli.Saidi@arm.com                    # probably a fluke; ignore it
4877618SAli.Saidi@arm.com                    com_pfx = ''
4887618SAli.Saidi@arm.com        # recalculate length in case com_pfx was modified
4897618SAli.Saidi@arm.com        com_pfx_len = len(com_pfx)
4907618SAli.Saidi@arm.com        def fmt(files):
4917618SAli.Saidi@arm.com            f = map(lambda s: s[com_pfx_len:], files)
4927618SAli.Saidi@arm.com            return ', '.join(f)
4937739Sgblack@eecs.umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4946121Snate@binkert.org
4953940Ssaidi@eecs.umich.eduExport('Transform')
4966121Snate@binkert.org
4977739Sgblack@eecs.umich.edu# enable the regression script to use the termcap
4987739Sgblack@eecs.umich.edumain['TERMCAP'] = termcap
4997739Sgblack@eecs.umich.edu
5007739Sgblack@eecs.umich.eduif GetOption('verbose'):
5017739Sgblack@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
5027739Sgblack@eecs.umich.edu        return Action(action, *args, **kwargs)
5033918Ssaidi@eecs.umich.eduelse:
5043918Ssaidi@eecs.umich.edu    MakeAction = Action
5053940Ssaidi@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
5063918Ssaidi@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
5073918Ssaidi@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
5086157Snate@binkert.org    main['SWIGCOMSTR']      = Transform("SWIG")
5096157Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
5106157Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
5116157Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5125397Ssaidi@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
5135397Ssaidi@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
5146121Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
5156121Snate@binkert.orgExport('MakeAction')
5166121Snate@binkert.org
5176121Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
5186121Snate@binkert.orgmain['LTO_CCFLAGS'] = []
5196121Snate@binkert.orgmain['LTO_LDFLAGS'] = []
5205397Ssaidi@eecs.umich.edu
5211851SN/A# According to the readme, tcmalloc works best if the compiler doesn't
5221851SN/A# assume that we're using the builtin malloc and friends. These flags
5237739Sgblack@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
524955SN/A# compiler we're using.
5253053Sstever@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
5266121Snate@binkert.org
5273053Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5283053Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5293053Sstever@eecs.umich.edu
5303053Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5313053Sstever@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5326654Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
5333053Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
5344742Sstever@eecs.umich.edu    Exit(1)
5354742Sstever@eecs.umich.edu
5363053Sstever@eecs.umich.edu# Set up default C++ compiler flags
5373053Sstever@eecs.umich.eduif main['GCC'] or main['CLANG']:
5383053Sstever@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
5393053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
5406654Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5413053Sstever@eecs.umich.edu    # Enable -Wall and then disable the few warnings that we
5423053Sstever@eecs.umich.edu    # consistently violate
5433053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5443053Sstever@eecs.umich.edu    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5452667Sstever@eecs.umich.edu    # actually use that name, so we stick with c++0x
5464554Sbinkertn@umich.edu    main.Append(CXXFLAGS=['-std=c++0x'])
5476121Snate@binkert.org    # Add selected sanity checks from -Wextra
5482667Sstever@eecs.umich.edu    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5494554Sbinkertn@umich.edu                          '-Woverloaded-virtual'])
5504554Sbinkertn@umich.eduelse:
5514554Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5526121Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
5534554Sbinkertn@umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5544554Sbinkertn@umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
5554554Sbinkertn@umich.edu    if not CXX_version:
5564781Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5574554Sbinkertn@umich.edu               termcap.Normal
5584554Sbinkertn@umich.edu    else:
5592667Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
5604554Sbinkertn@umich.edu    print "       If you're trying to use a compiler other than GCC"
5614554Sbinkertn@umich.edu    print "       or clang, there appears to be something wrong with your"
5624554Sbinkertn@umich.edu    print "       environment."
5634554Sbinkertn@umich.edu    print "       "
5642667Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5654554Sbinkertn@umich.edu    print "       above you will need to ease fix SConstruct and "
5662667Sstever@eecs.umich.edu    print "       src/SConscript to support that compiler."
5674554Sbinkertn@umich.edu    Exit(1)
5686121Snate@binkert.org
5692667Sstever@eecs.umich.eduif main['GCC']:
5705522Snate@binkert.org    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5715522Snate@binkert.org    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5725522Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5735522Snate@binkert.org    if compareVersions(gcc_version, "4.4") < 0:
5745522Snate@binkert.org        print 'Error: gcc version 4.4 or newer required.'
5755522Snate@binkert.org        print '       Installed version:', gcc_version
5765522Snate@binkert.org        Exit(1)
5775522Snate@binkert.org
5785522Snate@binkert.org    main['GCC_VERSION'] = gcc_version
5795522Snate@binkert.org
5805522Snate@binkert.org    # Check for versions with bugs
5815522Snate@binkert.org    if not compareVersions(gcc_version, '4.4.1') or \
5825522Snate@binkert.org       not compareVersions(gcc_version, '4.4.2'):
5835522Snate@binkert.org        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5845522Snate@binkert.org        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5855522Snate@binkert.org
5865522Snate@binkert.org    # LTO support is only really working properly from 4.6 and beyond
5875522Snate@binkert.org    if compareVersions(gcc_version, '4.6') >= 0:
5885522Snate@binkert.org        # Add the appropriate Link-Time Optimization (LTO) flags
5895522Snate@binkert.org        # unless LTO is explicitly turned off. Note that these flags
5905522Snate@binkert.org        # are only used by the fast target.
5915522Snate@binkert.org        if not GetOption('no_lto'):
5925522Snate@binkert.org            # Pass the LTO flag when compiling to produce GIMPLE
5935522Snate@binkert.org            # output, we merely create the flags here and only append
5945522Snate@binkert.org            # them later/
5955522Snate@binkert.org            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5962638Sstever@eecs.umich.edu
5972638Sstever@eecs.umich.edu            # Use the same amount of jobs for LTO as we are running
5986121Snate@binkert.org            # scons with, we hardcode the use of the linker plugin
5993716Sstever@eecs.umich.edu            # which requires either gold or GNU ld >= 2.21
6005522Snate@binkert.org            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
6015522Snate@binkert.org                                   '-fuse-linker-plugin']
6025522Snate@binkert.org
6035522Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6045522Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6055522Snate@binkert.org
6061858SN/Aelif main['CLANG']:
6075227Ssaidi@eecs.umich.edu    # Check for a supported version of clang, >= 2.9 is needed to
6085227Ssaidi@eecs.umich.edu    # support similar features as gcc 4.4. See
6095227Ssaidi@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
6105227Ssaidi@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
6116654Snate@binkert.org    clang_version_match = clang_version_re.match(CXX_version)
6126654Snate@binkert.org    if (clang_version_match):
6137769SAli.Saidi@ARM.com        clang_version = clang_version_match.groups()[0]
6147769SAli.Saidi@ARM.com        if compareVersions(clang_version, "2.9") < 0:
6157769SAli.Saidi@ARM.com            print 'Error: clang version 2.9 or newer required.'
6167769SAli.Saidi@ARM.com            print '       Installed version:', clang_version
6175227Ssaidi@eecs.umich.edu            Exit(1)
6185227Ssaidi@eecs.umich.edu    else:
6195227Ssaidi@eecs.umich.edu        print 'Error: Unable to determine clang version.'
6205204Sstever@gmail.com        Exit(1)
6215204Sstever@gmail.com
6225204Sstever@gmail.com    # clang has a few additional warnings that we disable,
6235204Sstever@gmail.com    # tautological comparisons are allowed due to unsigned integers
6245204Sstever@gmail.com    # being compared to constants that happen to be 0, and extraneous
6255204Sstever@gmail.com    # parantheses are allowed due to Ruby's printing of the AST,
6265204Sstever@gmail.com    # finally self assignments are allowed as the generated CPU code
6275204Sstever@gmail.com    # is relying on this
6285204Sstever@gmail.com    main.Append(CCFLAGS=['-Wno-tautological-compare',
6295204Sstever@gmail.com                         '-Wno-parentheses',
6305204Sstever@gmail.com                         '-Wno-self-assign'])
6315204Sstever@gmail.com
6325204Sstever@gmail.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6335204Sstever@gmail.com
6345204Sstever@gmail.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6355204Sstever@gmail.com    # opposed to libstdc++, as the later is dated.
6365204Sstever@gmail.com    if sys.platform == "darwin":
6376121Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
6385204Sstever@gmail.com        main.Append(LIBS=['c++'])
6393118Sstever@eecs.umich.edu
6403118Sstever@eecs.umich.eduelse:
6413118Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6423118Sstever@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
6433118Sstever@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6445863Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
6453118Sstever@eecs.umich.edu    if not CXX_version:
6465863Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6473118Sstever@eecs.umich.edu               termcap.Normal
6487457Snate@binkert.org    else:
6497457Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
6505863Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
6515863Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
6525863Snate@binkert.org    print "       environment."
6535863Snate@binkert.org    print "       "
6545863Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6555863Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
6565863Snate@binkert.org    print "       src/SConscript to support that compiler."
6576003Snate@binkert.org    Exit(1)
6585863Snate@binkert.org
6595863Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
6605863Snate@binkert.orgmain['YACCFLAGS'] = '-d'
6616120Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
6625863Snate@binkert.org
6635863Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
6645863Snate@binkert.org# extra 'qdo' every time we run scons.
6656120Snate@binkert.orgif main['BATCH']:
6666120Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6675863Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6685863Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6696120Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6705863Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6716121Snate@binkert.org
6726121Snate@binkert.orgif sys.platform == 'cygwin':
6735863Snate@binkert.org    # cygwin has some header file issues...
6747727SAli.Saidi@ARM.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
6757727SAli.Saidi@ARM.com
6767727SAli.Saidi@ARM.com# Check for the protobuf compiler
6777727SAli.Saidi@ARM.comprotoc_version = readCommand([main['PROTOC'], '--version'],
6787727SAli.Saidi@ARM.com                             exception='').split()
6797727SAli.Saidi@ARM.com
6805863Snate@binkert.org# First two words should be "libprotoc x.y.z"
6813118Sstever@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6825863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
6833118Sstever@eecs.umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6843118Sstever@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' + \
6855863Snate@binkert.org        termcap.Normal
6865863Snate@binkert.org    main['PROTOC'] = False
6875863Snate@binkert.orgelse:
6885863Snate@binkert.org    # Based on the availability of the compress stream wrappers,
6893118Sstever@eecs.umich.edu    # require 2.1.0
6903483Ssaidi@eecs.umich.edu    min_protoc_version = '2.1.0'
6913494Ssaidi@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6923494Ssaidi@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
6933483Ssaidi@eecs.umich.edu            'Warning: protoc version', min_protoc_version, \
6943483Ssaidi@eecs.umich.edu            'or newer required.\n' + \
6953483Ssaidi@eecs.umich.edu            '         Installed version:', protoc_version[1], \
6963053Sstever@eecs.umich.edu            termcap.Normal
6973053Sstever@eecs.umich.edu        main['PROTOC'] = False
6983918Ssaidi@eecs.umich.edu    else:
6993053Sstever@eecs.umich.edu        # Attempt to determine the appropriate include path and
7003053Sstever@eecs.umich.edu        # library path using pkg-config, that means we also need to
7013053Sstever@eecs.umich.edu        # check for pkg-config. Note that it is possible to use
7023053Sstever@eecs.umich.edu        # protobuf without the involvement of pkg-config. Later on we
7033053Sstever@eecs.umich.edu        # check go a library config check and at that point the test
7047840Snate@binkert.org        # will fail if libprotobuf cannot be found.
7057865Sgblack@eecs.umich.edu        if readCommand(['pkg-config', '--version'], exception=''):
7067865Sgblack@eecs.umich.edu            try:
7077865Sgblack@eecs.umich.edu                # Attempt to establish what linking flags to add for protobuf
7087865Sgblack@eecs.umich.edu                # using pkg-config
7097865Sgblack@eecs.umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7107840Snate@binkert.org            except:
7117840Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
7127840Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
7137840Snate@binkert.org                    termcap.Normal
7141858SN/A
7151858SN/A# Check for SWIG
7161858SN/Aif not main.has_key('SWIG'):
7171858SN/A    print 'Error: SWIG utility not found.'
7181858SN/A    print '       Please install (see http://www.swig.org) and retry.'
7191858SN/A    Exit(1)
7205863Snate@binkert.org
7215863Snate@binkert.org# Check for appropriate SWIG version
7225863Snate@binkert.orgswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7235863Snate@binkert.org# First 3 words should be "SWIG Version x.y.z"
7246121Snate@binkert.orgif len(swig_version) < 3 or \
7251858SN/A        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7265863Snate@binkert.org    print 'Error determining SWIG version.'
7275863Snate@binkert.org    Exit(1)
7285863Snate@binkert.org
7295863Snate@binkert.orgmin_swig_version = '1.3.34'
7305863Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
7312139SN/A    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7324202Sbinkertn@umich.edu    print '       Installed version:', swig_version[2]
7334202Sbinkertn@umich.edu    Exit(1)
7342139SN/A
7356994Snate@binkert.org# Older versions of swig do not play well with more recent versions of
7366994Snate@binkert.org# gcc due to assumptions on implicit includes (cstddef) and use of
7376994Snate@binkert.org# namespaces
7386994Snate@binkert.orgif main['GCC'] and compareVersions(gcc_version, '4.6') > 0 and \
7396994Snate@binkert.org        compareVersions(swig_version[2], '2') < 0:
7406994Snate@binkert.org    print '\n' + termcap.Yellow + termcap.Bold + \
7416994Snate@binkert.org        'Warning: SWIG 1.x cause issues with gcc 4.6 and later.\n' + \
7426994Snate@binkert.org        termcap.Normal + \
7436994Snate@binkert.org        'Use SWIG 2.x to avoid assumptions on implicit includes\n' + \
7446994Snate@binkert.org        'and use of namespaces\n'
7456994Snate@binkert.org
7466994Snate@binkert.org# Set up SWIG flags & scanner
7476994Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7486994Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
7496994Snate@binkert.org
7506994Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
7516994Snate@binkert.org# stuff for some reason
7526994Snate@binkert.orgscanners = []
7536994Snate@binkert.orgfor scanner in main['SCANNERS']:
7546994Snate@binkert.org    skeys = scanner.skeys
7556994Snate@binkert.org    if skeys == '.i':
7566994Snate@binkert.org        continue
7576994Snate@binkert.org
7586994Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7596994Snate@binkert.org        continue
7606994Snate@binkert.org
7616994Snate@binkert.org    scanners.append(scanner)
7626994Snate@binkert.org
7632155SN/A# add the new swig scanner that we like better
7645863Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
7651869SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7661869SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7675863Snate@binkert.org
7685863Snate@binkert.org# replace the scanners list that has what we want
7694202Sbinkertn@umich.edumain['SCANNERS'] = scanners
7706108Snate@binkert.org
7716108Snate@binkert.org# Add a custom Check function to the Configure context so that we can
7726108Snate@binkert.org# figure out if the compiler adds leading underscores to global
7736108Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
7744202Sbinkertn@umich.edu# use for embedding the python code.
7755863Snate@binkert.orgdef CheckLeading(context):
7768474Sgblack@eecs.umich.edu    context.Message("Checking for leading underscore in global variables...")
7778474Sgblack@eecs.umich.edu    # 1) Define a global variable called x from asm so the C compiler
7785742Snate@binkert.org    #    won't change the symbol at all.
7798268Ssteve.reinhardt@amd.com    # 2) Declare that variable.
7808268Ssteve.reinhardt@amd.com    # 3) Use the variable
7818268Ssteve.reinhardt@amd.com    #
7825742Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
7835341Sstever@gmail.com    # link because the external symbol 'x' will be called '_x' which
7848474Sgblack@eecs.umich.edu    # was defined by the asm statement.  If the compiler does not
7858474Sgblack@eecs.umich.edu    # prepend an underscore, this will not successfully link because
7865342Sstever@gmail.com    # '_x' will have been defined by assembly, while the C portion of
7874202Sbinkertn@umich.edu    # the code will be trying to use 'x'
7884202Sbinkertn@umich.edu    ret = context.TryLink('''
7894202Sbinkertn@umich.edu        asm(".globl _x; _x: .byte 0");
7905863Snate@binkert.org        extern int x;
7915863Snate@binkert.org        int main() { return x; }
7925863Snate@binkert.org        ''', extension=".c")
7936994Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
7946994Snate@binkert.org    context.Result(ret)
7956994Snate@binkert.org    return ret
7965863Snate@binkert.org
7978152Ssteve.reinhardt@amd.com# Platform-specific configuration.  Note again that we assume that all
7988152Ssteve.reinhardt@amd.com# builds under a given build root run on the same host platform.
7995863Snate@binkert.orgconf = Configure(main,
8005863Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
8015863Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
8025863Snate@binkert.org                 custom_tests = { 'CheckLeading' : CheckLeading })
8035863Snate@binkert.org
8045863Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
8055863Snate@binkert.org# way so don't need to check the return code.
8065863Snate@binkert.orgconf.CheckLeading()
8075863Snate@binkert.org
8085863Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8097840Snate@binkert.orgtry:
8105863Snate@binkert.org    import platform
8115863Snate@binkert.org    uname = platform.uname()
8125952Ssaidi@eecs.umich.edu    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8131869SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8141858SN/A            main.Append(CCFLAGS=['-arch', 'x86_64'])
8155863Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
8168297Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8178152Ssteve.reinhardt@amd.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
8187840Snate@binkert.orgexcept:
8197840Snate@binkert.org    pass
8201858SN/A
821955SN/A# Recent versions of scons substitute a "Null" object for Configure()
822955SN/A# when configuration isn't necessary, e.g., if the "--help" option is
8231869SN/A# present.  Unfortuantely this Null object always returns false,
8241869SN/A# breaking all our configuration checks.  We replace it with our own
8251869SN/A# more optimistic null object that returns True instead.
8261869SN/Aif not conf:
8271869SN/A    def NullCheck(*args, **kwargs):
8285863Snate@binkert.org        return True
8295863Snate@binkert.org
8305863Snate@binkert.org    class NullConf:
8311869SN/A        def __init__(self, env):
8325863Snate@binkert.org            self.env = env
8331869SN/A        def Finish(self):
8345863Snate@binkert.org            return self.env
8351869SN/A        def __getattr__(self, mname):
8361869SN/A            return NullCheck
8371869SN/A
8381869SN/A    conf = NullConf(main)
8398483Sgblack@eecs.umich.edu
8401869SN/A# Cache build files in the supplied directory.
8411869SN/Aif main['M5_BUILD_CACHE']:
8421869SN/A    print 'Using build cache located at', main['M5_BUILD_CACHE']
8431869SN/A    CacheDir(main['M5_BUILD_CACHE'])
8445863Snate@binkert.org
8455863Snate@binkert.org# Find Python include and library directories for embedding the
8461869SN/A# interpreter. We rely on python-config to resolve the appropriate
8475863Snate@binkert.org# includes and linker flags. ParseConfig does not seem to understand
8485863Snate@binkert.org# the more exotic linker flags such as -Xlinker and -export-dynamic so
8493356Sbinkertn@umich.edu# we add them explicitly below. If you want to link in an alternate
8503356Sbinkertn@umich.edu# version of python, see above for instructions on how to invoke
8513356Sbinkertn@umich.edu# scons with the appropriate PATH set.
8523356Sbinkertn@umich.edupy_includes = readCommand(['python-config', '--includes'],
8533356Sbinkertn@umich.edu                          exception='').split()
8544781Snate@binkert.org# Strip the -I from the include folders before adding them to the
8555863Snate@binkert.org# CPPPATH
8565863Snate@binkert.orgmain.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
8571869SN/A
8581869SN/A# Read the linker flags and split them into libraries and other link
8591869SN/A# flags. The libraries are added later through the call the CheckLib.
8606121Snate@binkert.orgpy_ld_flags = readCommand(['python-config', '--ldflags'], exception='').split()
8611869SN/Apy_libs = []
8622638Sstever@eecs.umich.edufor lib in py_ld_flags:
8636121Snate@binkert.org     if not lib.startswith('-l'):
8646121Snate@binkert.org         main.Append(LINKFLAGS=[lib])
8652638Sstever@eecs.umich.edu     else:
8665749Scws3k@cs.virginia.edu         lib = lib[2:]
8676121Snate@binkert.org         if lib not in py_libs:
8686121Snate@binkert.org             py_libs.append(lib)
8695749Scws3k@cs.virginia.edu
8701869SN/A# verify that this stuff works
8711869SN/Aif not conf.CheckHeader('Python.h', '<>'):
8723546Sgblack@eecs.umich.edu    print "Error: can't find Python.h header in", py_includes
8733546Sgblack@eecs.umich.edu    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8743546Sgblack@eecs.umich.edu    Exit(1)
8753546Sgblack@eecs.umich.edu
8766121Snate@binkert.orgfor lib in py_libs:
8775863Snate@binkert.org    if not conf.CheckLib(lib):
8783546Sgblack@eecs.umich.edu        print "Error: can't find library %s required by python" % lib
8793546Sgblack@eecs.umich.edu        Exit(1)
8803546Sgblack@eecs.umich.edu
8813546Sgblack@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
8824781Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8834781Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8846658Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
8856658Snate@binkert.org       Exit(1)
8864781Snate@binkert.org
8873546Sgblack@eecs.umich.edu# Check for zlib.  If the check passes, libz will be automatically
8883546Sgblack@eecs.umich.edu# added to the LIBS environment variable.
8893546Sgblack@eecs.umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
8903546Sgblack@eecs.umich.edu    print 'Error: did not find needed zlib compression library '\
8917756SAli.Saidi@ARM.com          'and/or zlib.h header file.'
8927816Ssteve.reinhardt@amd.com    print '       Please install zlib and try again.'
8933546Sgblack@eecs.umich.edu    Exit(1)
8943546Sgblack@eecs.umich.edu
8953546Sgblack@eecs.umich.edu# If we have the protobuf compiler, also make sure we have the
8963546Sgblack@eecs.umich.edu# development libraries. If the check passes, libprotobuf will be
8974202Sbinkertn@umich.edu# automatically added to the LIBS environment variable. After
8983546Sgblack@eecs.umich.edu# this, we can use the HAVE_PROTOBUF flag to determine if we have
8993546Sgblack@eecs.umich.edu# got both protoc and libprotobuf available.
9003546Sgblack@eecs.umich.edumain['HAVE_PROTOBUF'] = main['PROTOC'] and \
901955SN/A    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
902955SN/A                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
903955SN/A
904955SN/A# If we have the compiler but not the library, print another warning.
9055863Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9065863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9075343Sstever@gmail.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
9085343Sstever@gmail.com    '       Please install libprotobuf-dev for tracing support.' + \
9096121Snate@binkert.org    termcap.Normal
9105863Snate@binkert.org
9114773Snate@binkert.org# Check for librt.
9125863Snate@binkert.orghave_posix_clock = \
9132632Sstever@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
9145863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
9152023SN/A    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9165863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
9175863Snate@binkert.org
9185863Snate@binkert.orghave_posix_timers = \
9195863Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
9205863Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
9215863Snate@binkert.org
9225863Snate@binkert.orgif conf.CheckLib('tcmalloc'):
9235863Snate@binkert.org    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9245863Snate@binkert.orgelif conf.CheckLib('tcmalloc_minimal'):
9252632Sstever@eecs.umich.edu    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9265863Snate@binkert.orgelse:
9272023SN/A    print termcap.Yellow + termcap.Bold + \
9282632Sstever@eecs.umich.edu          "You can get a 12% performance improvement by installing tcmalloc "\
9295863Snate@binkert.org          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
9305342Sstever@gmail.com          termcap.Normal
9315863Snate@binkert.org
9322632Sstever@eecs.umich.eduif not have_posix_clock:
9335863Snate@binkert.org    print "Can't find library for POSIX clocks."
9345863Snate@binkert.org
9358267Ssteve.reinhardt@amd.com# Check for <fenv.h> (C99 FP environment control)
9368120Sgblack@eecs.umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
9378267Ssteve.reinhardt@amd.comif not have_fenv:
9388267Ssteve.reinhardt@amd.com    print "Warning: Header file <fenv.h> not found."
9398267Ssteve.reinhardt@amd.com    print "         This host has no IEEE FP rounding mode control."
9408267Ssteve.reinhardt@amd.com
9418267Ssteve.reinhardt@amd.com# Check if we should enable KVM-based hardware virtualization. The API
9428267Ssteve.reinhardt@amd.com# we rely on exists since version 2.6.36 of the kernel, but somehow
9438267Ssteve.reinhardt@amd.com# the KVM_API_VERSION does not reflect the change. We test for one of
9448267Ssteve.reinhardt@amd.com# the types as a fall back.
9458267Ssteve.reinhardt@amd.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>') and \
9465863Snate@binkert.org    conf.CheckTypeSize('struct kvm_xsave', '#include <linux/kvm.h>') != 0
9475863Snate@binkert.orgif not have_kvm:
9485863Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
9492632Sstever@eecs.umich.edu        "disabling KVM support."
9508267Ssteve.reinhardt@amd.com
9518267Ssteve.reinhardt@amd.com# Check if the requested target ISA is compatible with the host
9528267Ssteve.reinhardt@amd.comdef is_isa_kvm_compatible(isa):
9532632Sstever@eecs.umich.edu    isa_comp_table = {
9541888SN/A        "arm" : ( "armv7l" ),
9555863Snate@binkert.org        "x86" : ( "x86_64" ),
9565863Snate@binkert.org        }
9571858SN/A    try:
9588120Sgblack@eecs.umich.edu        import platform
9598120Sgblack@eecs.umich.edu        host_isa = platform.machine()
9607756SAli.Saidi@ARM.com    except:
9612598SN/A        print "Warning: Failed to determine host ISA."
9625863Snate@binkert.org        return False
9631858SN/A
9641858SN/A    return host_isa in isa_comp_table.get(isa, [])
9651858SN/A
9665863Snate@binkert.org
9671858SN/A######################################################################
9681858SN/A#
9691858SN/A# Finish the configuration
9705863Snate@binkert.org#
9711871SN/Amain = conf.Finish()
9721858SN/A
9731858SN/A######################################################################
9741858SN/A#
9751858SN/A# Collect all non-global variables
9765863Snate@binkert.org#
9775863Snate@binkert.org
9781869SN/A# Define the universe of supported ISAs
9791965SN/Aall_isa_list = [ ]
9807739Sgblack@eecs.umich.eduExport('all_isa_list')
9811965SN/A
9828482Snilay@cs.wisc.educlass CpuModel(object):
9838482Snilay@cs.wisc.edu    '''The CpuModel class encapsulates everything the ISA parser needs to
9848482Snilay@cs.wisc.edu    know about a particular CPU model.'''
9858482Snilay@cs.wisc.edu
9868482Snilay@cs.wisc.edu    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9872761Sstever@eecs.umich.edu    dict = {}
9885863Snate@binkert.org    list = []
9891869SN/A    defaults = []
9905863Snate@binkert.org
9912667Sstever@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
9921869SN/A    def __init__(self, name, filename, includes, strings, default=False):
9931869SN/A        self.name = name           # name of model
9942929Sktlim@umich.edu        self.filename = filename   # filename for output exec code
9952929Sktlim@umich.edu        self.includes = includes   # include files needed in exec file
9965863Snate@binkert.org        # The 'strings' dict holds all the per-CPU symbols we can
9972929Sktlim@umich.edu        # substitute into templates etc.
998955SN/A        self.strings = strings
9998120Sgblack@eecs.umich.edu
10008120Sgblack@eecs.umich.edu        # This cpu is enabled by default
10018120Sgblack@eecs.umich.edu        self.default = default
10028120Sgblack@eecs.umich.edu
10038120Sgblack@eecs.umich.edu        # Add self to dict
10048120Sgblack@eecs.umich.edu        if name in CpuModel.dict:
10058120Sgblack@eecs.umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
10068120Sgblack@eecs.umich.edu        CpuModel.dict[name] = self
10078120Sgblack@eecs.umich.edu        CpuModel.list.append(name)
10088120Sgblack@eecs.umich.edu
10098120Sgblack@eecs.umich.eduExport('CpuModel')
10108120Sgblack@eecs.umich.edu
1011# Sticky variables get saved in the variables file so they persist from
1012# one invocation to the next (unless overridden, in which case the new
1013# value becomes sticky).
1014sticky_vars = Variables(args=ARGUMENTS)
1015Export('sticky_vars')
1016
1017# Sticky variables that should be exported
1018export_vars = []
1019Export('export_vars')
1020
1021# For Ruby
1022all_protocols = []
1023Export('all_protocols')
1024protocol_dirs = []
1025Export('protocol_dirs')
1026slicc_includes = []
1027Export('slicc_includes')
1028
1029# Walk the tree and execute all SConsopts scripts that wil add to the
1030# above variables
1031if not GetOption('verbose'):
1032    print "Reading SConsopts"
1033for bdir in [ base_dir ] + extras_dir_list:
1034    if not isdir(bdir):
1035        print "Error: directory '%s' does not exist" % bdir
1036        Exit(1)
1037    for root, dirs, files in os.walk(bdir):
1038        if 'SConsopts' in files:
1039            if GetOption('verbose'):
1040                print "Reading", joinpath(root, 'SConsopts')
1041            SConscript(joinpath(root, 'SConsopts'))
1042
1043all_isa_list.sort()
1044
1045sticky_vars.AddVariables(
1046    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1047    ListVariable('CPU_MODELS', 'CPU models',
1048                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1049                 sorted(CpuModel.list)),
1050    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1051                 False),
1052    BoolVariable('SS_COMPATIBLE_FP',
1053                 'Make floating-point results compatible with SimpleScalar',
1054                 False),
1055    BoolVariable('USE_SSE2',
1056                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1057                 False),
1058    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1059    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1060    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1061    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1062    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1063                  all_protocols),
1064    )
1065
1066# These variables get exported to #defines in config/*.hh (see src/SConscript).
1067export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1068                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
1069
1070###################################################
1071#
1072# Define a SCons builder for configuration flag headers.
1073#
1074###################################################
1075
1076# This function generates a config header file that #defines the
1077# variable symbol to the current variable setting (0 or 1).  The source
1078# operands are the name of the variable and a Value node containing the
1079# value of the variable.
1080def build_config_file(target, source, env):
1081    (variable, value) = [s.get_contents() for s in source]
1082    f = file(str(target[0]), 'w')
1083    print >> f, '#define', variable, value
1084    f.close()
1085    return None
1086
1087# Combine the two functions into a scons Action object.
1088config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1089
1090# The emitter munges the source & target node lists to reflect what
1091# we're really doing.
1092def config_emitter(target, source, env):
1093    # extract variable name from Builder arg
1094    variable = str(target[0])
1095    # True target is config header file
1096    target = joinpath('config', variable.lower() + '.hh')
1097    val = env[variable]
1098    if isinstance(val, bool):
1099        # Force value to 0/1
1100        val = int(val)
1101    elif isinstance(val, str):
1102        val = '"' + val + '"'
1103
1104    # Sources are variable name & value (packaged in SCons Value nodes)
1105    return ([target], [Value(variable), Value(val)])
1106
1107config_builder = Builder(emitter = config_emitter, action = config_action)
1108
1109main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1110
1111# libelf build is shared across all configs in the build root.
1112main.SConscript('ext/libelf/SConscript',
1113                variant_dir = joinpath(build_root, 'libelf'))
1114
1115# gzstream build is shared across all configs in the build root.
1116main.SConscript('ext/gzstream/SConscript',
1117                variant_dir = joinpath(build_root, 'gzstream'))
1118
1119# libfdt build is shared across all configs in the build root.
1120main.SConscript('ext/libfdt/SConscript',
1121                variant_dir = joinpath(build_root, 'libfdt'))
1122
1123# fputils build is shared across all configs in the build root.
1124main.SConscript('ext/fputils/SConscript',
1125                variant_dir = joinpath(build_root, 'fputils'))
1126
1127###################################################
1128#
1129# This function is used to set up a directory with switching headers
1130#
1131###################################################
1132
1133main['ALL_ISA_LIST'] = all_isa_list
1134def make_switching_dir(dname, switch_headers, env):
1135    # Generate the header.  target[0] is the full path of the output
1136    # header to generate.  'source' is a dummy variable, since we get the
1137    # list of ISAs from env['ALL_ISA_LIST'].
1138    def gen_switch_hdr(target, source, env):
1139        fname = str(target[0])
1140        f = open(fname, 'w')
1141        isa = env['TARGET_ISA'].lower()
1142        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1143        f.close()
1144
1145    # Build SCons Action object. 'varlist' specifies env vars that this
1146    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1147    # should get re-executed.
1148    switch_hdr_action = MakeAction(gen_switch_hdr,
1149                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1150
1151    # Instantiate actions for each header
1152    for hdr in switch_headers:
1153        env.Command(hdr, [], switch_hdr_action)
1154Export('make_switching_dir')
1155
1156###################################################
1157#
1158# Define build environments for selected configurations.
1159#
1160###################################################
1161
1162for variant_path in variant_paths:
1163    print "Building in", variant_path
1164
1165    # Make a copy of the build-root environment to use for this config.
1166    env = main.Clone()
1167    env['BUILDDIR'] = variant_path
1168
1169    # variant_dir is the tail component of build path, and is used to
1170    # determine the build parameters (e.g., 'ALPHA_SE')
1171    (build_root, variant_dir) = splitpath(variant_path)
1172
1173    # Set env variables according to the build directory config.
1174    sticky_vars.files = []
1175    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1176    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1177    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1178    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1179    if isfile(current_vars_file):
1180        sticky_vars.files.append(current_vars_file)
1181        print "Using saved variables file %s" % current_vars_file
1182    else:
1183        # Build dir-specific variables file doesn't exist.
1184
1185        # Make sure the directory is there so we can create it later
1186        opt_dir = dirname(current_vars_file)
1187        if not isdir(opt_dir):
1188            mkdir(opt_dir)
1189
1190        # Get default build variables from source tree.  Variables are
1191        # normally determined by name of $VARIANT_DIR, but can be
1192        # overridden by '--default=' arg on command line.
1193        default = GetOption('default')
1194        opts_dir = joinpath(main.root.abspath, 'build_opts')
1195        if default:
1196            default_vars_files = [joinpath(build_root, 'variables', default),
1197                                  joinpath(opts_dir, default)]
1198        else:
1199            default_vars_files = [joinpath(opts_dir, variant_dir)]
1200        existing_files = filter(isfile, default_vars_files)
1201        if existing_files:
1202            default_vars_file = existing_files[0]
1203            sticky_vars.files.append(default_vars_file)
1204            print "Variables file %s not found,\n  using defaults in %s" \
1205                  % (current_vars_file, default_vars_file)
1206        else:
1207            print "Error: cannot find variables file %s or " \
1208                  "default file(s) %s" \
1209                  % (current_vars_file, ' or '.join(default_vars_files))
1210            Exit(1)
1211
1212    # Apply current variable settings to env
1213    sticky_vars.Update(env)
1214
1215    help_texts["local_vars"] += \
1216        "Build variables for %s:\n" % variant_dir \
1217                 + sticky_vars.GenerateHelpText(env)
1218
1219    # Process variable settings.
1220
1221    if not have_fenv and env['USE_FENV']:
1222        print "Warning: <fenv.h> not available; " \
1223              "forcing USE_FENV to False in", variant_dir + "."
1224        env['USE_FENV'] = False
1225
1226    if not env['USE_FENV']:
1227        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1228        print "         FP results may deviate slightly from other platforms."
1229
1230    if env['EFENCE']:
1231        env.Append(LIBS=['efence'])
1232
1233    if env['USE_KVM']:
1234        if not have_kvm:
1235            print "Warning: Can not enable KVM, host seems to lack KVM support"
1236            env['USE_KVM'] = False
1237        elif not have_posix_timers:
1238            print "Warning: Can not enable KVM, host seems to lack support " \
1239                "for POSIX timers"
1240            env['USE_KVM'] = False
1241        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1242            print "Info: KVM support disabled due to unsupported host and " \
1243                "target ISA combination"
1244            env['USE_KVM'] = False
1245
1246    # Save sticky variable settings back to current variables file
1247    sticky_vars.Save(current_vars_file, env)
1248
1249    if env['USE_SSE2']:
1250        env.Append(CCFLAGS=['-msse2'])
1251
1252    # The src/SConscript file sets up the build rules in 'env' according
1253    # to the configured variables.  It returns a list of environments,
1254    # one for each variant build (debug, opt, etc.)
1255    envList = SConscript('src/SConscript', variant_dir = variant_path,
1256                         exports = 'env')
1257
1258    # Set up the regression tests for each build.
1259    for e in envList:
1260        SConscript('tests/SConscript',
1261                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1262                   exports = { 'env' : e }, duplicate = False)
1263
1264# base help text
1265Help('''
1266Usage: scons [scons options] [build variables] [target(s)]
1267
1268Extra scons options:
1269%(options)s
1270
1271Global build variables:
1272%(global_vars)s
1273
1274%(local_vars)s
1275''' % help_texts)
1276