SConstruct revision 9590
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
45871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
51762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
6955SN/A# All rights reserved.
7955SN/A#
8955SN/A# Redistribution and use in source and binary forms, with or without
9955SN/A# modification, are permitted provided that the following conditions are
10955SN/A# met: redistributions of source code must retain the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer;
12955SN/A# redistributions in binary form must reproduce the above copyright
13955SN/A# notice, this list of conditions and the following disclaimer in the
14955SN/A# documentation and/or other materials provided with the distribution;
15955SN/A# neither the name of the copyright holders nor the names of its
16955SN/A# contributors may be used to endorse or promote products derived from
17955SN/A# this software without specific prior written permission.
18955SN/A#
19955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
302665Ssaidi@eecs.umich.edu#
312665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
325863Snate@binkert.org#          Nathan Binkert
33955SN/A
34955SN/A###################################################
35955SN/A#
36955SN/A# SCons top-level build description (SConstruct) file.
37955SN/A#
382632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
392632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
402632Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
412632Sstever@eecs.umich.edu# the optimized full-system version).
42955SN/A#
432632Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
442632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
452761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
462632Sstever@eecs.umich.edu# built for the same host system.
472632Sstever@eecs.umich.edu#
482632Sstever@eecs.umich.edu# Examples:
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
512761Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
522632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
532632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
562761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
572761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
582761Sstever@eecs.umich.edu#   file.
592632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
602632Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
632632Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
642632Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
652632Sstever@eecs.umich.edu# options as well.
66955SN/A#
67955SN/A###################################################
68955SN/A
695863Snate@binkert.org# Check for recent-enough Python and SCons versions.
705863Snate@binkert.orgtry:
715863Snate@binkert.org    # Really old versions of scons only take two options for the
725863Snate@binkert.org    # function, so check once without the revision and once with the
735863Snate@binkert.org    # revision, the first instance will fail for stuff other than
745863Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
755863Snate@binkert.org    EnsureSConsVersion(0, 98)
765863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
775863Snate@binkert.orgexcept SystemExit, e:
785863Snate@binkert.org    print """
795863Snate@binkert.orgFor more details, see:
805863Snate@binkert.org    http://gem5.org/Dependencies
815863Snate@binkert.org"""
825863Snate@binkert.org    raise
835863Snate@binkert.org
845863Snate@binkert.org# We ensure the python version early because we have stuff that
855863Snate@binkert.org# requires python 2.4
865863Snate@binkert.orgtry:
875863Snate@binkert.org    EnsurePythonVersion(2, 4)
885863Snate@binkert.orgexcept SystemExit, e:
895863Snate@binkert.org    print """
905863Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
915863Snate@binkert.orgeither (1) rearranging your PATH so that scons finds the non-default
925863Snate@binkert.org'python' first or (2) explicitly invoking an alternative interpreter
935863Snate@binkert.orgon the scons script.
945863Snate@binkert.org
955863Snate@binkert.orgFor more details, see:
965863Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
975863Snate@binkert.org"""
985863Snate@binkert.org    raise
995863Snate@binkert.org
1006654Snate@binkert.org# Global Python includes
101955SN/Aimport os
1025396Ssaidi@eecs.umich.eduimport re
1035863Snate@binkert.orgimport subprocess
1045863Snate@binkert.orgimport sys
1054202Sbinkertn@umich.edu
1065863Snate@binkert.orgfrom os import mkdir, environ
1075863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1085863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1095863Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
110955SN/A
1116654Snate@binkert.org# SCons includes
1125273Sstever@gmail.comimport SCons
1135871Snate@binkert.orgimport SCons.Node
1145273Sstever@gmail.com
1156655Snate@binkert.orgextra_python_paths = [
1166655Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1176655Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1186655Snate@binkert.org    ]
1196655Snate@binkert.org
1206655Snate@binkert.orgsys.path[1:1] = extra_python_paths
1215871Snate@binkert.org
1226654Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1235396Ssaidi@eecs.umich.edufrom m5.util.terminal import get_termcap
1248120Sgblack@eecs.umich.edu
1258120Sgblack@eecs.umich.eduhelp_texts = {
1268120Sgblack@eecs.umich.edu    "options" : "",
1278120Sgblack@eecs.umich.edu    "global_vars" : "",
1288120Sgblack@eecs.umich.edu    "local_vars" : ""
1298120Sgblack@eecs.umich.edu}
1308120Sgblack@eecs.umich.edu
1318120Sgblack@eecs.umich.eduExport("help_texts")
1328120Sgblack@eecs.umich.edu
1338120Sgblack@eecs.umich.edu
1348120Sgblack@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1358120Sgblack@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1368120Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1378120Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1388120Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1398120Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1408120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1418120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1428120Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1438120Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1448120Sgblack@eecs.umich.edu# we can just use AddOption directly.
1458120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1468120Sgblack@eecs.umich.edu    col_width = 30
1478120Sgblack@eecs.umich.edu
1488120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1498120Sgblack@eecs.umich.edu    if "help" in kwargs:
1508120Sgblack@eecs.umich.edu        length = len(help)
1518120Sgblack@eecs.umich.edu        if length >= col_width:
1528120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1538120Sgblack@eecs.umich.edu        else:
1548120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1558120Sgblack@eecs.umich.edu        help += kwargs["help"]
1568120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1578120Sgblack@eecs.umich.edu
1588120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1598120Sgblack@eecs.umich.edu
1607816Ssteve.reinhardt@amd.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1617816Ssteve.reinhardt@amd.com               help="Add color to abbreviated scons output")
1627816Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1637816Ssteve.reinhardt@amd.com               help="Don't add color to abbreviated scons output")
1647816Ssteve.reinhardt@amd.comAddLocalOption('--default', dest='default', type='string', action='store',
1657816Ssteve.reinhardt@amd.com               help='Override which build_opts file to use for defaults')
1667816Ssteve.reinhardt@amd.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1677816Ssteve.reinhardt@amd.com               help='Disable style checking hooks')
1687816Ssteve.reinhardt@amd.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1695871Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1705871Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1716121Snate@binkert.org               help='Update test reference outputs')
1725871Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1735871Snate@binkert.org               help='Print full tool command lines')
1746003Snate@binkert.org
1756655Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
176955SN/A
1775871Snate@binkert.org########################################################################
1785871Snate@binkert.org#
1795871Snate@binkert.org# Set up the main build environment.
1805871Snate@binkert.org#
181955SN/A########################################################################
1826121Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1836121Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1846121Snate@binkert.org                 'RANLIB', 'SWIG' ])
1851533SN/A
1866655Snate@binkert.orguse_prefixes = [
1876655Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
1886655Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
1896655Snate@binkert.org    "CCACHE_",      # ccache (caching compiler wrapper) configuration
1905871Snate@binkert.org    "CCC_",         # clang static analyzer configuration
1915871Snate@binkert.org    ]
1925863Snate@binkert.org
1935871Snate@binkert.orguse_env = {}
1945871Snate@binkert.orgfor key,val in os.environ.iteritems():
1955871Snate@binkert.org    if key in use_vars or \
1965871Snate@binkert.org            any([key.startswith(prefix) for prefix in use_prefixes]):
1975871Snate@binkert.org        use_env[key] = val
1985863Snate@binkert.org
1996121Snate@binkert.orgmain = Environment(ENV=use_env)
2005863Snate@binkert.orgmain.Decider('MD5-timestamp')
2015871Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
2024678Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
2034678Snate@binkert.org
2044678Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2054678Snate@binkert.org
2064678Snate@binkert.org# Check that we have a C/C++ compiler
2074678Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2084678Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2094678Snate@binkert.org    Exit(1)
2104678Snate@binkert.org
2114678Snate@binkert.org# Check that swig is present
2124678Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2137827Snate@binkert.org    print "swig is not installed (package swig on Ubuntu and RedHat)"
2147827Snate@binkert.org    Exit(1)
2156121Snate@binkert.org
2164678Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2175871Snate@binkert.org# as well
2185871Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2195871Snate@binkert.org
2205871Snate@binkert.org########################################################################
2215871Snate@binkert.org#
2225871Snate@binkert.org# Mercurial Stuff.
2235871Snate@binkert.org#
2245871Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2255871Snate@binkert.org# extra things.
2265871Snate@binkert.org#
2275871Snate@binkert.org########################################################################
2285871Snate@binkert.org
2295871Snate@binkert.orghgdir = main.root.Dir(".hg")
2305990Ssaidi@eecs.umich.edu
2315871Snate@binkert.orgmercurial_style_message = """
2325871Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2335871Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
2344678Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
2356654Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2365871Snate@binkert.org
2375871Snate@binkert.orgmercurial_style_hook = """
2385871Snate@binkert.org# The following lines were automatically added by gem5/SConstruct
2395871Snate@binkert.org# to provide the gem5 style-checking hooks
2405871Snate@binkert.org[extensions]
2415871Snate@binkert.orgstyle = %s/util/style.py
2428120Sgblack@eecs.umich.edu
2435871Snate@binkert.org[hooks]
2445871Snate@binkert.orgpretxncommit.style = python:style.check_style
2454678Snate@binkert.orgpre-qrefresh.style = python:style.check_style
2465871Snate@binkert.org# End of SConstruct additions
2474678Snate@binkert.org
2485871Snate@binkert.org""" % (main.root.abspath)
2495871Snate@binkert.org
2505871Snate@binkert.orgmercurial_lib_not_found = """
2515871Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2525871Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
2535871Snate@binkert.orghook. It is important.
2545871Snate@binkert.org"""
2555871Snate@binkert.org
2565871Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
2576121Snate@binkert.org# Skip this if --ignore-style was specified, there's no .hg dir to
2586121Snate@binkert.org# install a hook in, or there's no interactive terminal to prompt.
2595863Snate@binkert.orgif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
260955SN/A    style_hook = True
261955SN/A    try:
2622632Sstever@eecs.umich.edu        from mercurial import ui
2632632Sstever@eecs.umich.edu        ui = ui.ui()
264955SN/A        ui.readconfig(hgdir.File('hgrc').abspath)
265955SN/A        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
266955SN/A                     ui.config('hooks', 'pre-qrefresh.style', None)
267955SN/A    except ImportError:
2685863Snate@binkert.org        print mercurial_lib_not_found
269955SN/A
2702632Sstever@eecs.umich.edu    if not style_hook:
2712632Sstever@eecs.umich.edu        print mercurial_style_message,
2722632Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
2732632Sstever@eecs.umich.edu        try:
2742632Sstever@eecs.umich.edu            raw_input()
2752632Sstever@eecs.umich.edu        except:
2762632Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
2772632Sstever@eecs.umich.edu            sys.exit(1)
2782632Sstever@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2792632Sstever@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
2802632Sstever@eecs.umich.edu        try:
2812632Sstever@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
2822632Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
2833718Sstever@eecs.umich.edu            hgrc.close()
2843718Sstever@eecs.umich.edu        except:
2853718Sstever@eecs.umich.edu            print "Error updating", hgrc_path
2863718Sstever@eecs.umich.edu            sys.exit(1)
2873718Sstever@eecs.umich.edu
2885863Snate@binkert.org
2895863Snate@binkert.org###################################################
2903718Sstever@eecs.umich.edu#
2913718Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
2926121Snate@binkert.org# the target(s).
2935863Snate@binkert.org#
2943718Sstever@eecs.umich.edu###################################################
2953718Sstever@eecs.umich.edu
2962634Sstever@eecs.umich.edu# Find default configuration & binary.
2972634Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2985863Snate@binkert.org
2992638Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
3002632Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
3012632Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
3022632Sstever@eecs.umich.edu        if l[i] == elt:
3032632Sstever@eecs.umich.edu            return i
3042632Sstever@eecs.umich.edu    raise ValueError, "element not found"
3052632Sstever@eecs.umich.edu
3061858SN/A# Take a list of paths (or SCons Nodes) and return a list with all
3073716Sstever@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
3082638Sstever@eecs.umich.edu# relative to the launch directory unless a different root is provided
3092638Sstever@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
3102638Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
3112638Sstever@eecs.umich.edu            for p in path_list]
3122638Sstever@eecs.umich.edu
3132638Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
3142638Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
3155863Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3165863Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
3175863Snate@binkert.org# follow 'build' in the build path.
318955SN/A
3195341Sstever@gmail.com# The funky assignment to "[:]" is needed to replace the list contents
3205341Sstever@gmail.com# in place rather than reassign the symbol to a new list, which
3215863Snate@binkert.org# doesn't work (obviously!).
3227756SAli.Saidi@ARM.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3235341Sstever@gmail.com
3246121Snate@binkert.org# Generate a list of the unique build roots and configs that the
3254494Ssaidi@eecs.umich.edu# collected targets reference.
3266121Snate@binkert.orgvariant_paths = []
3271105SN/Abuild_root = None
3282667Sstever@eecs.umich.edufor t in BUILD_TARGETS:
3292667Sstever@eecs.umich.edu    path_dirs = t.split('/')
3302667Sstever@eecs.umich.edu    try:
3312667Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3326121Snate@binkert.org    except:
3332667Sstever@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3345341Sstever@gmail.com        Exit(1)
3355863Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3365341Sstever@gmail.com    if not build_root:
3375341Sstever@gmail.com        build_root = this_build_root
3385341Sstever@gmail.com    else:
3395863Snate@binkert.org        if this_build_root != build_root:
3405341Sstever@gmail.com            print "Error: build targets not under same build root\n"\
3415341Sstever@gmail.com                  "  %s\n  %s" % (build_root, this_build_root)
3425341Sstever@gmail.com            Exit(1)
3435863Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
3445341Sstever@gmail.com    if variant_path not in variant_paths:
3455341Sstever@gmail.com        variant_paths.append(variant_path)
3465341Sstever@gmail.com
3475341Sstever@gmail.com# Make sure build_root exists (might not if this is the first build there)
3485341Sstever@gmail.comif not isdir(build_root):
3495341Sstever@gmail.com    mkdir(build_root)
3505341Sstever@gmail.commain['BUILDROOT'] = build_root
3515341Sstever@gmail.com
3525341Sstever@gmail.comExport('main')
3535341Sstever@gmail.com
3548120Sgblack@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
3555341Sstever@gmail.com
3568120Sgblack@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
3575341Sstever@gmail.com# when you use emacs to edit a file in the target dir, as emacs moves
3588120Sgblack@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3596121Snate@binkert.org# (soft) links work better.
3606121Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
3615397Ssaidi@eecs.umich.edu
3625397Ssaidi@eecs.umich.edu#
3637727SAli.Saidi@ARM.com# Set up global sticky variables... these are common to an entire build
3645341Sstever@gmail.com# tree (not specific to a particular build like ALPHA_SE)
3656168Snate@binkert.org#
3666168Snate@binkert.org
3675341Sstever@gmail.comglobal_vars_file = joinpath(build_root, 'variables.global')
3688120Sgblack@eecs.umich.edu
3698120Sgblack@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3708120Sgblack@eecs.umich.edu
3716814Sgblack@eecs.umich.eduglobal_vars.AddVariables(
3725863Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3738120Sgblack@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3745341Sstever@gmail.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3755863Snate@binkert.org    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3765341Sstever@gmail.com    ('BATCH', 'Use batch pool for build and tests', False),
3776121Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3786121Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3796121Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
3805742Snate@binkert.org    )
3815742Snate@binkert.org
3825341Sstever@gmail.com# Update main environment with values from ARGUMENTS & global_vars_file
3835742Snate@binkert.orgglobal_vars.Update(main)
3845742Snate@binkert.orghelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3855341Sstever@gmail.com
3866017Snate@binkert.org# Save sticky variable settings back to current variables file
3876121Snate@binkert.orgglobal_vars.Save(global_vars_file, main)
3886017Snate@binkert.org
3897816Ssteve.reinhardt@amd.com# Parse EXTRAS variable to build list of all directories where we're
3907756SAli.Saidi@ARM.com# look for sources etc.  This list is exported as extras_dir_list.
3917756SAli.Saidi@ARM.combase_dir = main.srcdir.abspath
3927756SAli.Saidi@ARM.comif main['EXTRAS']:
3937756SAli.Saidi@ARM.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3947756SAli.Saidi@ARM.comelse:
3957756SAli.Saidi@ARM.com    extras_dir_list = []
3967756SAli.Saidi@ARM.com
3977756SAli.Saidi@ARM.comExport('base_dir')
3987816Ssteve.reinhardt@amd.comExport('extras_dir_list')
3997816Ssteve.reinhardt@amd.com
4007816Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
4017816Ssteve.reinhardt@amd.commain.Append(CPPPATH=[Dir('ext')])
4027816Ssteve.reinhardt@amd.com
4037816Ssteve.reinhardt@amd.comdef strip_build_path(path, env):
4047816Ssteve.reinhardt@amd.com    path = str(path)
4057816Ssteve.reinhardt@amd.com    variant_base = env['BUILDROOT'] + os.path.sep
4067816Ssteve.reinhardt@amd.com    if path.startswith(variant_base):
4077816Ssteve.reinhardt@amd.com        path = path[len(variant_base):]
4087756SAli.Saidi@ARM.com    elif path.startswith('build/'):
4097816Ssteve.reinhardt@amd.com        path = path[6:]
4107816Ssteve.reinhardt@amd.com    return path
4117816Ssteve.reinhardt@amd.com
4127816Ssteve.reinhardt@amd.com# Generate a string of the form:
4137816Ssteve.reinhardt@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
4147816Ssteve.reinhardt@amd.com# to print while building.
4157816Ssteve.reinhardt@amd.comclass Transform(object):
4167816Ssteve.reinhardt@amd.com    # all specific color settings should be here and nowhere else
4177816Ssteve.reinhardt@amd.com    tool_color = termcap.Normal
4187816Ssteve.reinhardt@amd.com    pfx_color = termcap.Yellow
4197816Ssteve.reinhardt@amd.com    srcs_color = termcap.Yellow + termcap.Bold
4207816Ssteve.reinhardt@amd.com    arrow_color = termcap.Blue + termcap.Bold
4217816Ssteve.reinhardt@amd.com    tgts_color = termcap.Yellow + termcap.Bold
4227816Ssteve.reinhardt@amd.com
4237816Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
4247816Ssteve.reinhardt@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
4257816Ssteve.reinhardt@amd.com                      + self.pfx_color + "%s" \
4267816Ssteve.reinhardt@amd.com                      + self.srcs_color + "%s" \
4277816Ssteve.reinhardt@amd.com                      + self.arrow_color + " -> " \
4287816Ssteve.reinhardt@amd.com                      + self.tgts_color + "%s" \
4297816Ssteve.reinhardt@amd.com                      + termcap.Normal
4307816Ssteve.reinhardt@amd.com        self.max_sources = max_sources
4317816Ssteve.reinhardt@amd.com
4327816Ssteve.reinhardt@amd.com    def __call__(self, target, source, env, for_signature=None):
4337816Ssteve.reinhardt@amd.com        # truncate source list according to max_sources param
4347816Ssteve.reinhardt@amd.com        source = source[0:self.max_sources]
4357816Ssteve.reinhardt@amd.com        def strip(f):
4367816Ssteve.reinhardt@amd.com            return strip_build_path(str(f), env)
4377816Ssteve.reinhardt@amd.com        if len(source) > 0:
4387816Ssteve.reinhardt@amd.com            srcs = map(strip, source)
4397816Ssteve.reinhardt@amd.com        else:
4407816Ssteve.reinhardt@amd.com            srcs = ['']
4417816Ssteve.reinhardt@amd.com        tgts = map(strip, target)
4427816Ssteve.reinhardt@amd.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4437816Ssteve.reinhardt@amd.com        # operation that has nothing to do with paths.
4447816Ssteve.reinhardt@amd.com        com_pfx = os.path.commonprefix(srcs + tgts)
4457816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4467816Ssteve.reinhardt@amd.com        if com_pfx:
4477816Ssteve.reinhardt@amd.com            # do some cleanup and sanity checking on common prefix
4487816Ssteve.reinhardt@amd.com            if com_pfx[-1] == ".":
4497816Ssteve.reinhardt@amd.com                # prefix matches all but file extension: ok
4507816Ssteve.reinhardt@amd.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4517816Ssteve.reinhardt@amd.com                com_pfx = com_pfx[0:-1]
4527816Ssteve.reinhardt@amd.com            elif com_pfx[-1] == "/":
4537816Ssteve.reinhardt@amd.com                # common prefix is directory path: OK
4547816Ssteve.reinhardt@amd.com                pass
4557816Ssteve.reinhardt@amd.com            else:
4567816Ssteve.reinhardt@amd.com                src0_len = len(srcs[0])
4577816Ssteve.reinhardt@amd.com                tgt0_len = len(tgts[0])
4587816Ssteve.reinhardt@amd.com                if src0_len == com_pfx_len:
4597816Ssteve.reinhardt@amd.com                    # source is a substring of target, OK
4607816Ssteve.reinhardt@amd.com                    pass
4617816Ssteve.reinhardt@amd.com                elif tgt0_len == com_pfx_len:
4627816Ssteve.reinhardt@amd.com                    # target is a substring of source, need to back up to
4637816Ssteve.reinhardt@amd.com                    # avoid empty string on RHS of arrow
4647816Ssteve.reinhardt@amd.com                    sep_idx = com_pfx.rfind(".")
4657816Ssteve.reinhardt@amd.com                    if sep_idx != -1:
4667816Ssteve.reinhardt@amd.com                        com_pfx = com_pfx[0:sep_idx]
4677816Ssteve.reinhardt@amd.com                    else:
4687816Ssteve.reinhardt@amd.com                        com_pfx = ''
4697816Ssteve.reinhardt@amd.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4707756SAli.Saidi@ARM.com                    # still splitting at file extension: ok
4718120Sgblack@eecs.umich.edu                    pass
4727756SAli.Saidi@ARM.com                else:
4737756SAli.Saidi@ARM.com                    # probably a fluke; ignore it
4747756SAli.Saidi@ARM.com                    com_pfx = ''
4757756SAli.Saidi@ARM.com        # recalculate length in case com_pfx was modified
4767816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4777816Ssteve.reinhardt@amd.com        def fmt(files):
4787816Ssteve.reinhardt@amd.com            f = map(lambda s: s[com_pfx_len:], files)
4797816Ssteve.reinhardt@amd.com            return ', '.join(f)
4807816Ssteve.reinhardt@amd.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4817816Ssteve.reinhardt@amd.com
4827816Ssteve.reinhardt@amd.comExport('Transform')
4837816Ssteve.reinhardt@amd.com
4847816Ssteve.reinhardt@amd.com# enable the regression script to use the termcap
4857816Ssteve.reinhardt@amd.commain['TERMCAP'] = termcap
4867756SAli.Saidi@ARM.com
4877756SAli.Saidi@ARM.comif GetOption('verbose'):
4886654Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
4896654Snate@binkert.org        return Action(action, *args, **kwargs)
4905871Snate@binkert.orgelse:
4916121Snate@binkert.org    MakeAction = Action
4926121Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
4936121Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
4946121Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
4953940Ssaidi@eecs.umich.edu    main['SWIGCOMSTR']      = Transform("SWIG")
4963918Ssaidi@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
4973918Ssaidi@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
4981858SN/A    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4996121Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
5007739Sgblack@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
5017739Sgblack@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
5026143Snate@binkert.orgExport('MakeAction')
5037739Sgblack@eecs.umich.edu
5047618SAli.Saidi@arm.com# Initialize the Link-Time Optimization (LTO) flags
5057618SAli.Saidi@arm.commain['LTO_CCFLAGS'] = []
5067618SAli.Saidi@arm.commain['LTO_LDFLAGS'] = []
5077618SAli.Saidi@arm.com
5087618SAli.Saidi@arm.com# According to the readme, tcmalloc works best if the compiler doesn't
5097618SAli.Saidi@arm.com# assume that we're using the builtin malloc and friends. These flags
5107618SAli.Saidi@arm.com# are compiler-specific, so we need to set them after we detect which
5117739Sgblack@eecs.umich.edu# compiler we're using.
5126121Snate@binkert.orgmain['TCMALLOC_CCFLAGS'] = []
5133940Ssaidi@eecs.umich.edu
5146121Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5157739Sgblack@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5167739Sgblack@eecs.umich.edu
5177739Sgblack@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5187739Sgblack@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5197739Sgblack@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
5207739Sgblack@eecs.umich.edu    print 'Error: How can we have two at the same time?'
5213918Ssaidi@eecs.umich.edu    Exit(1)
5223918Ssaidi@eecs.umich.edu
5233940Ssaidi@eecs.umich.edu# Set up default C++ compiler flags
5243918Ssaidi@eecs.umich.eduif main['GCC'] or main['CLANG']:
5253918Ssaidi@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
5266157Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
5276157Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5286157Snate@binkert.org    # Enable -Wall and then disable the few warnings that we
5296157Snate@binkert.org    # consistently violate
5305397Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5315397Ssaidi@eecs.umich.edu    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5326121Snate@binkert.org    # actually use that name, so we stick with c++0x
5336121Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++0x'])
5346121Snate@binkert.org    # Add selected sanity checks from -Wextra
5356121Snate@binkert.org    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5366121Snate@binkert.org                          '-Woverloaded-virtual'])
5376121Snate@binkert.orgelse:
5385397Ssaidi@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5391851SN/A    print "Don't know what compiler options to use for your compiler."
5401851SN/A    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5417739Sgblack@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
542955SN/A    if not CXX_version:
5433053Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5446121Snate@binkert.org               termcap.Normal
5453053Sstever@eecs.umich.edu    else:
5463053Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
5473053Sstever@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
5483053Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
5493053Sstever@eecs.umich.edu    print "       environment."
5506654Snate@binkert.org    print "       "
5513053Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5524742Sstever@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
5534742Sstever@eecs.umich.edu    print "       src/SConscript to support that compiler."
5543053Sstever@eecs.umich.edu    Exit(1)
5553053Sstever@eecs.umich.edu
5563053Sstever@eecs.umich.eduif main['GCC']:
5573053Sstever@eecs.umich.edu    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5586654Snate@binkert.org    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5593053Sstever@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5603053Sstever@eecs.umich.edu    if compareVersions(gcc_version, "4.4") < 0:
5613053Sstever@eecs.umich.edu        print 'Error: gcc version 4.4 or newer required.'
5623053Sstever@eecs.umich.edu        print '       Installed version:', gcc_version
5632667Sstever@eecs.umich.edu        Exit(1)
5644554Sbinkertn@umich.edu
5656121Snate@binkert.org    main['GCC_VERSION'] = gcc_version
5662667Sstever@eecs.umich.edu
5674554Sbinkertn@umich.edu    # Check for versions with bugs
5684554Sbinkertn@umich.edu    if not compareVersions(gcc_version, '4.4.1') or \
5694554Sbinkertn@umich.edu       not compareVersions(gcc_version, '4.4.2'):
5706121Snate@binkert.org        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5714554Sbinkertn@umich.edu        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5724554Sbinkertn@umich.edu
5734554Sbinkertn@umich.edu    # LTO support is only really working properly from 4.6 and beyond
5744781Snate@binkert.org    if compareVersions(gcc_version, '4.6') >= 0:
5754554Sbinkertn@umich.edu        # Add the appropriate Link-Time Optimization (LTO) flags
5764554Sbinkertn@umich.edu        # unless LTO is explicitly turned off. Note that these flags
5772667Sstever@eecs.umich.edu        # are only used by the fast target.
5784554Sbinkertn@umich.edu        if not GetOption('no_lto'):
5794554Sbinkertn@umich.edu            # Pass the LTO flag when compiling to produce GIMPLE
5804554Sbinkertn@umich.edu            # output, we merely create the flags here and only append
5814554Sbinkertn@umich.edu            # them later/
5822667Sstever@eecs.umich.edu            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5834554Sbinkertn@umich.edu
5842667Sstever@eecs.umich.edu            # Use the same amount of jobs for LTO as we are running
5854554Sbinkertn@umich.edu            # scons with, we hardcode the use of the linker plugin
5866121Snate@binkert.org            # which requires either gold or GNU ld >= 2.21
5872667Sstever@eecs.umich.edu            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5885522Snate@binkert.org                                   '-fuse-linker-plugin']
5895522Snate@binkert.org
5905522Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
5915522Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
5925522Snate@binkert.org
5935522Snate@binkert.orgelif main['CLANG']:
5945522Snate@binkert.org    # Check for a supported version of clang, >= 2.9 is needed to
5955522Snate@binkert.org    # support similar features as gcc 4.4. See
5965522Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
5975522Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
5985522Snate@binkert.org    clang_version_match = clang_version_re.match(CXX_version)
5995522Snate@binkert.org    if (clang_version_match):
6005522Snate@binkert.org        clang_version = clang_version_match.groups()[0]
6015522Snate@binkert.org        if compareVersions(clang_version, "2.9") < 0:
6025522Snate@binkert.org            print 'Error: clang version 2.9 or newer required.'
6035522Snate@binkert.org            print '       Installed version:', clang_version
6045522Snate@binkert.org            Exit(1)
6055522Snate@binkert.org    else:
6065522Snate@binkert.org        print 'Error: Unable to determine clang version.'
6075522Snate@binkert.org        Exit(1)
6085522Snate@binkert.org
6095522Snate@binkert.org    # clang has a few additional warnings that we disable,
6105522Snate@binkert.org    # tautological comparisons are allowed due to unsigned integers
6115522Snate@binkert.org    # being compared to constants that happen to be 0, and extraneous
6125522Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
6135522Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
6142638Sstever@eecs.umich.edu    # is relying on this
6152638Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-tautological-compare',
6166121Snate@binkert.org                         '-Wno-parentheses',
6173716Sstever@eecs.umich.edu                         '-Wno-self-assign'])
6185522Snate@binkert.org
6195522Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6205522Snate@binkert.org
6215522Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6225522Snate@binkert.org    # opposed to libstdc++ to make the transition from TR1 to
6235522Snate@binkert.org    # C++11. See http://libcxx.llvm.org. However, clang has chosen a
6241858SN/A    # strict implementation of the C++11 standard, and does not allow
6255227Ssaidi@eecs.umich.edu    # incomplete types in template arguments (besides unique_ptr and
6265227Ssaidi@eecs.umich.edu    # shared_ptr), and the libc++ STL containers create problems in
6275227Ssaidi@eecs.umich.edu    # combination with the current gem5 code. For now, we stick with
6285227Ssaidi@eecs.umich.edu    # libstdc++ and use the TR1 namespace.
6296654Snate@binkert.org    # if sys.platform == "darwin":
6306654Snate@binkert.org    #     main.Append(CXXFLAGS=['-stdlib=libc++'])
6317769SAli.Saidi@ARM.com
6327769SAli.Saidi@ARM.comelse:
6337769SAli.Saidi@ARM.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6347769SAli.Saidi@ARM.com    print "Don't know what compiler options to use for your compiler."
6355227Ssaidi@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6365227Ssaidi@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6375227Ssaidi@eecs.umich.edu    if not CXX_version:
6385204Sstever@gmail.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6395204Sstever@gmail.com               termcap.Normal
6405204Sstever@gmail.com    else:
6415204Sstever@gmail.com        print CXX_version.replace('\n', '<nl>')
6425204Sstever@gmail.com    print "       If you're trying to use a compiler other than GCC"
6435204Sstever@gmail.com    print "       or clang, there appears to be something wrong with your"
6445204Sstever@gmail.com    print "       environment."
6455204Sstever@gmail.com    print "       "
6465204Sstever@gmail.com    print "       If you are trying to use a compiler other than those listed"
6475204Sstever@gmail.com    print "       above you will need to ease fix SConstruct and "
6485204Sstever@gmail.com    print "       src/SConscript to support that compiler."
6495204Sstever@gmail.com    Exit(1)
6505204Sstever@gmail.com
6515204Sstever@gmail.com# Set up common yacc/bison flags (needed for Ruby)
6525204Sstever@gmail.commain['YACCFLAGS'] = '-d'
6535204Sstever@gmail.commain['YACCHXXFILESUFFIX'] = '.hh'
6545204Sstever@gmail.com
6556121Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
6565204Sstever@gmail.com# extra 'qdo' every time we run scons.
6573118Sstever@eecs.umich.eduif main['BATCH']:
6583118Sstever@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6593118Sstever@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6603118Sstever@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6613118Sstever@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6625863Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6633118Sstever@eecs.umich.edu
6645863Snate@binkert.orgif sys.platform == 'cygwin':
6653118Sstever@eecs.umich.edu    # cygwin has some header file issues...
6667457Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
6677457Snate@binkert.org
6685863Snate@binkert.org# Check for the protobuf compiler
6695863Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
6705863Snate@binkert.org                             exception='').split()
6715863Snate@binkert.org
6725863Snate@binkert.org# First two words should be "libprotoc x.y.z"
6735863Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6745863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
6756003Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6765863Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
6775863Snate@binkert.org        termcap.Normal
6785863Snate@binkert.org    main['PROTOC'] = False
6796120Snate@binkert.orgelse:
6805863Snate@binkert.org    # Based on the availability of the compress stream wrappers,
6815863Snate@binkert.org    # require 2.1.0
6825863Snate@binkert.org    min_protoc_version = '2.1.0'
6836120Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6846120Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
6855863Snate@binkert.org            'Warning: protoc version', min_protoc_version, \
6865863Snate@binkert.org            'or newer required.\n' + \
6876120Snate@binkert.org            '         Installed version:', protoc_version[1], \
6885863Snate@binkert.org            termcap.Normal
6896121Snate@binkert.org        main['PROTOC'] = False
6906121Snate@binkert.org    else:
6915863Snate@binkert.org        # Attempt to determine the appropriate include path and
6927727SAli.Saidi@ARM.com        # library path using pkg-config, that means we also need to
6937727SAli.Saidi@ARM.com        # check for pkg-config. Note that it is possible to use
6947727SAli.Saidi@ARM.com        # protobuf without the involvement of pkg-config. Later on we
6957727SAli.Saidi@ARM.com        # check go a library config check and at that point the test
6967727SAli.Saidi@ARM.com        # will fail if libprotobuf cannot be found.
6977727SAli.Saidi@ARM.com        if readCommand(['pkg-config', '--version'], exception=''):
6985863Snate@binkert.org            try:
6993118Sstever@eecs.umich.edu                # Attempt to establish what linking flags to add for protobuf
7005863Snate@binkert.org                # using pkg-config
7013118Sstever@eecs.umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7023118Sstever@eecs.umich.edu            except:
7035863Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
7045863Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
7055863Snate@binkert.org                    termcap.Normal
7065863Snate@binkert.org
7073118Sstever@eecs.umich.edu# Check for SWIG
7083483Ssaidi@eecs.umich.eduif not main.has_key('SWIG'):
7093494Ssaidi@eecs.umich.edu    print 'Error: SWIG utility not found.'
7103494Ssaidi@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
7113483Ssaidi@eecs.umich.edu    Exit(1)
7123483Ssaidi@eecs.umich.edu
7133483Ssaidi@eecs.umich.edu# Check for appropriate SWIG version
7143053Sstever@eecs.umich.eduswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7153053Sstever@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
7163918Ssaidi@eecs.umich.eduif len(swig_version) < 3 or \
7173053Sstever@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7183053Sstever@eecs.umich.edu    print 'Error determining SWIG version.'
7193053Sstever@eecs.umich.edu    Exit(1)
7203053Sstever@eecs.umich.edu
7213053Sstever@eecs.umich.edumin_swig_version = '1.3.34'
7227840Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
7237865Sgblack@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7247865Sgblack@eecs.umich.edu    print '       Installed version:', swig_version[2]
7257865Sgblack@eecs.umich.edu    Exit(1)
7267865Sgblack@eecs.umich.edu
7277865Sgblack@eecs.umich.eduif swig_version[2] == "2.0.9":
7287840Snate@binkert.org    print '\n' + termcap.Yellow + termcap.Bold + \
7297840Snate@binkert.org        'Warning: SWIG version 2.0.9 sometimes generates broken code.\n' + \
7307840Snate@binkert.org        termcap.Normal + \
7317840Snate@binkert.org        'This problem only affects some platforms and some Python\n' + \
7321858SN/A        'versions. See the following SWIG bug report for details:\n' + \
7331858SN/A        'http://sourceforge.net/p/swig/bugs/1297/\n'
7341858SN/A
7351858SN/A
7361858SN/A# Set up SWIG flags & scanner
7371858SN/Aswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7385863Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
7395863Snate@binkert.org
7401859SN/A# filter out all existing swig scanners, they mess up the dependency
7415863Snate@binkert.org# stuff for some reason
7421858SN/Ascanners = []
7435863Snate@binkert.orgfor scanner in main['SCANNERS']:
7441858SN/A    skeys = scanner.skeys
7451859SN/A    if skeys == '.i':
7461859SN/A        continue
7476654Snate@binkert.org
7483053Sstever@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7496654Snate@binkert.org        continue
7503053Sstever@eecs.umich.edu
7513053Sstever@eecs.umich.edu    scanners.append(scanner)
7521859SN/A
7531859SN/A# add the new swig scanner that we like better
7541859SN/Afrom SCons.Scanner import ClassicCPP as CPPScanner
7551859SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7561859SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7571859SN/A
7581859SN/A# replace the scanners list that has what we want
7591859SN/Amain['SCANNERS'] = scanners
7601862SN/A
7611859SN/A# Add a custom Check function to the Configure context so that we can
7621859SN/A# figure out if the compiler adds leading underscores to global
7631859SN/A# variables.  This is needed for the autogenerated asm files that we
7645863Snate@binkert.org# use for embedding the python code.
7655863Snate@binkert.orgdef CheckLeading(context):
7665863Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
7675863Snate@binkert.org    # 1) Define a global variable called x from asm so the C compiler
7686121Snate@binkert.org    #    won't change the symbol at all.
7691858SN/A    # 2) Declare that variable.
7705863Snate@binkert.org    # 3) Use the variable
7715863Snate@binkert.org    #
7725863Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
7735863Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
7745863Snate@binkert.org    # was defined by the asm statement.  If the compiler does not
7752139SN/A    # prepend an underscore, this will not successfully link because
7764202Sbinkertn@umich.edu    # '_x' will have been defined by assembly, while the C portion of
7774202Sbinkertn@umich.edu    # the code will be trying to use 'x'
7782139SN/A    ret = context.TryLink('''
7796994Snate@binkert.org        asm(".globl _x; _x: .byte 0");
7806994Snate@binkert.org        extern int x;
7816994Snate@binkert.org        int main() { return x; }
7826994Snate@binkert.org        ''', extension=".c")
7836994Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
7846994Snate@binkert.org    context.Result(ret)
7856994Snate@binkert.org    return ret
7866994Snate@binkert.org
7876994Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
7886994Snate@binkert.org# builds under a given build root run on the same host platform.
7896994Snate@binkert.orgconf = Configure(main,
7906994Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
7916994Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
7926994Snate@binkert.org                 custom_tests = { 'CheckLeading' : CheckLeading })
7936994Snate@binkert.org
7946994Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
7956994Snate@binkert.org# way so don't need to check the return code.
7966994Snate@binkert.orgconf.CheckLeading()
7976994Snate@binkert.org
7986994Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
7996994Snate@binkert.orgtry:
8006994Snate@binkert.org    import platform
8016994Snate@binkert.org    uname = platform.uname()
8026994Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8036994Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8046994Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
8056994Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
8066994Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8072155SN/A            main.Append(ASFLAGS=['-arch', 'x86_64'])
8085863Snate@binkert.orgexcept:
8091869SN/A    pass
8101869SN/A
8115863Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
8125863Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
8134202Sbinkertn@umich.edu# present.  Unfortuantely this Null object always returns false,
8146108Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
8156108Snate@binkert.org# more optimistic null object that returns True instead.
8166108Snate@binkert.orgif not conf:
8176108Snate@binkert.org    def NullCheck(*args, **kwargs):
8184202Sbinkertn@umich.edu        return True
8195863Snate@binkert.org
8205742Snate@binkert.org    class NullConf:
8215742Snate@binkert.org        def __init__(self, env):
8225341Sstever@gmail.com            self.env = env
8235342Sstever@gmail.com        def Finish(self):
8245342Sstever@gmail.com            return self.env
8254202Sbinkertn@umich.edu        def __getattr__(self, mname):
8264202Sbinkertn@umich.edu            return NullCheck
8274202Sbinkertn@umich.edu
8285863Snate@binkert.org    conf = NullConf(main)
8295863Snate@binkert.org
8305863Snate@binkert.org# Find Python include and library directories for embedding the
8316994Snate@binkert.org# interpreter.  For consistency, we will use the same Python
8326994Snate@binkert.org# installation used to run scons (and thus this script).  If you want
8336994Snate@binkert.org# to link in an alternate version, see above for instructions on how
8345863Snate@binkert.org# to invoke scons with a different copy of the Python interpreter.
8355863Snate@binkert.orgfrom distutils import sysconfig
8365863Snate@binkert.org
8375863Snate@binkert.orgpy_getvar = sysconfig.get_config_var
8385863Snate@binkert.org
8395863Snate@binkert.orgpy_debug = getattr(sys, 'pydebug', False)
8405863Snate@binkert.orgpy_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
8415863Snate@binkert.org
8425863Snate@binkert.orgpy_general_include = sysconfig.get_python_inc()
8435863Snate@binkert.orgpy_platform_include = sysconfig.get_python_inc(plat_specific=True)
8445863Snate@binkert.orgpy_includes = [ py_general_include ]
8455863Snate@binkert.orgif py_platform_include != py_general_include:
8465863Snate@binkert.org    py_includes.append(py_platform_include)
8475863Snate@binkert.org
8487840Snate@binkert.orgpy_lib_path = [ py_getvar('LIBDIR') ]
8495863Snate@binkert.org# add the prefix/lib/pythonX.Y/config dir, but only if there is no
8505863Snate@binkert.org# shared library in prefix/lib/.
8515952Ssaidi@eecs.umich.eduif not py_getvar('Py_ENABLE_SHARED'):
8527450Sstever@gmail.com    py_lib_path.append(py_getvar('LIBPL'))
8531869SN/A    # Python requires the flags in LINKFORSHARED to be added the
8541858SN/A    # linker flags when linking with a statically with Python. Failing
8555863Snate@binkert.org    # to do so can lead to errors from the Python's dynamic module
8566108Snate@binkert.org    # loader at start up.
8576108Snate@binkert.org    main.Append(LINKFLAGS=[py_getvar('LINKFORSHARED').split()])
8587840Snate@binkert.org
8597840Snate@binkert.orgpy_libs = []
8601858SN/Afor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
861955SN/A    if not lib.startswith('-l'):
862955SN/A        # Python requires some special flags to link (e.g. -framework
8631869SN/A        # common on OS X systems), assume appending preserves order
8641869SN/A        main.Append(LINKFLAGS=[lib])
8651869SN/A    else:
8661869SN/A        lib = lib[2:]
8671869SN/A        if lib not in py_libs:
8685863Snate@binkert.org            py_libs.append(lib)
8695863Snate@binkert.orgpy_libs.append(py_version)
8705863Snate@binkert.org
8711869SN/Amain.Append(CPPPATH=py_includes)
8725863Snate@binkert.orgmain.Append(LIBPATH=py_lib_path)
8731869SN/A
8745863Snate@binkert.org# Cache build files in the supplied directory.
8751869SN/Aif main['M5_BUILD_CACHE']:
8761869SN/A    print 'Using build cache located at', main['M5_BUILD_CACHE']
8771869SN/A    CacheDir(main['M5_BUILD_CACHE'])
8781869SN/A
8791869SN/A
8805863Snate@binkert.org# verify that this stuff works
8815863Snate@binkert.orgif not conf.CheckHeader('Python.h', '<>'):
8821869SN/A    print "Error: can't find Python.h header in", py_includes
8831869SN/A    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8841869SN/A    Exit(1)
8851869SN/A
8861869SN/Afor lib in py_libs:
8871869SN/A    if not conf.CheckLib(lib):
8881869SN/A        print "Error: can't find library %s required by python" % lib
8895863Snate@binkert.org        Exit(1)
8905863Snate@binkert.org
8911869SN/A# On Solaris you need to use libsocket for socket ops
8925863Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8935863Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8943356Sbinkertn@umich.edu       print "Can't find library with socket calls (e.g. accept())"
8953356Sbinkertn@umich.edu       Exit(1)
8963356Sbinkertn@umich.edu
8973356Sbinkertn@umich.edu# Check for zlib.  If the check passes, libz will be automatically
8983356Sbinkertn@umich.edu# added to the LIBS environment variable.
8994781Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
9005863Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
9015863Snate@binkert.org          'and/or zlib.h header file.'
9021869SN/A    print '       Please install zlib and try again.'
9031869SN/A    Exit(1)
9041869SN/A
9056121Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
9061869SN/A# development libraries. If the check passes, libprotobuf will be
9072638Sstever@eecs.umich.edu# automatically added to the LIBS environment variable. After
9086121Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
9096121Snate@binkert.org# got both protoc and libprotobuf available.
9102638Sstever@eecs.umich.edumain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9115749Scws3k@cs.virginia.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9126121Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9136121Snate@binkert.org
9145749Scws3k@cs.virginia.edu# If we have the compiler but not the library, print another warning.
9151869SN/Aif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9161869SN/A    print termcap.Yellow + termcap.Bold + \
9173546Sgblack@eecs.umich.edu        'Warning: did not find protocol buffer library and/or headers.\n' + \
9183546Sgblack@eecs.umich.edu    '       Please install libprotobuf-dev for tracing support.' + \
9193546Sgblack@eecs.umich.edu    termcap.Normal
9203546Sgblack@eecs.umich.edu
9216121Snate@binkert.org# Check for librt.
9225863Snate@binkert.orghave_posix_clock = \
9233546Sgblack@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
9243546Sgblack@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);') or \
9253546Sgblack@eecs.umich.edu    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9263546Sgblack@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
9274781Snate@binkert.org
9284781Snate@binkert.orgif conf.CheckLib('tcmalloc_minimal'):
9296658Snate@binkert.org    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9306658Snate@binkert.orgelse:
9314781Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9323546Sgblack@eecs.umich.edu          "You can get a 12% performance improvement by installing tcmalloc "\
9333546Sgblack@eecs.umich.edu          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
9343546Sgblack@eecs.umich.edu          termcap.Normal
9353546Sgblack@eecs.umich.edu
9367756SAli.Saidi@ARM.comif not have_posix_clock:
9377816Ssteve.reinhardt@amd.com    print "Can't find library for POSIX clocks."
9383546Sgblack@eecs.umich.edu
9393546Sgblack@eecs.umich.edu# Check for <fenv.h> (C99 FP environment control)
9403546Sgblack@eecs.umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
9413546Sgblack@eecs.umich.eduif not have_fenv:
9424202Sbinkertn@umich.edu    print "Warning: Header file <fenv.h> not found."
9433546Sgblack@eecs.umich.edu    print "         This host has no IEEE FP rounding mode control."
9443546Sgblack@eecs.umich.edu
9453546Sgblack@eecs.umich.edu######################################################################
946955SN/A#
947955SN/A# Finish the configuration
948955SN/A#
949955SN/Amain = conf.Finish()
9505863Snate@binkert.org
9515863Snate@binkert.org######################################################################
9525343Sstever@gmail.com#
9535343Sstever@gmail.com# Collect all non-global variables
9546121Snate@binkert.org#
9555863Snate@binkert.org
9564773Snate@binkert.org# Define the universe of supported ISAs
9575863Snate@binkert.orgall_isa_list = [ ]
9582632Sstever@eecs.umich.eduExport('all_isa_list')
9595863Snate@binkert.org
9602023SN/Aclass CpuModel(object):
9615863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9625863Snate@binkert.org    know about a particular CPU model.'''
9635863Snate@binkert.org
9645863Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9655863Snate@binkert.org    dict = {}
9665863Snate@binkert.org    list = []
9675863Snate@binkert.org    defaults = []
9685863Snate@binkert.org
9695863Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
9702632Sstever@eecs.umich.edu    def __init__(self, name, filename, includes, strings, default=False):
9715863Snate@binkert.org        self.name = name           # name of model
9722023SN/A        self.filename = filename   # filename for output exec code
9732632Sstever@eecs.umich.edu        self.includes = includes   # include files needed in exec file
9745863Snate@binkert.org        # The 'strings' dict holds all the per-CPU symbols we can
9755342Sstever@gmail.com        # substitute into templates etc.
9765863Snate@binkert.org        self.strings = strings
9772632Sstever@eecs.umich.edu
9785863Snate@binkert.org        # This cpu is enabled by default
9795863Snate@binkert.org        self.default = default
9802632Sstever@eecs.umich.edu
9818120Sgblack@eecs.umich.edu        # Add self to dict
9828120Sgblack@eecs.umich.edu        if name in CpuModel.dict:
9838120Sgblack@eecs.umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
9848120Sgblack@eecs.umich.edu        CpuModel.dict[name] = self
9855863Snate@binkert.org        CpuModel.list.append(name)
9865863Snate@binkert.org
9875863Snate@binkert.orgExport('CpuModel')
9885863Snate@binkert.org
9892632Sstever@eecs.umich.edu# Sticky variables get saved in the variables file so they persist from
9905863Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
9915863Snate@binkert.org# value becomes sticky).
9922632Sstever@eecs.umich.edusticky_vars = Variables(args=ARGUMENTS)
9931888SN/AExport('sticky_vars')
9945863Snate@binkert.org
9955863Snate@binkert.org# Sticky variables that should be exported
9961858SN/Aexport_vars = []
9978120Sgblack@eecs.umich.eduExport('export_vars')
9988120Sgblack@eecs.umich.edu
9997756SAli.Saidi@ARM.com# For Ruby
10002598SN/Aall_protocols = []
10015863Snate@binkert.orgExport('all_protocols')
10021858SN/Aprotocol_dirs = []
10031858SN/AExport('protocol_dirs')
10041858SN/Aslicc_includes = []
10055863Snate@binkert.orgExport('slicc_includes')
10061858SN/A
10071858SN/A# Walk the tree and execute all SConsopts scripts that wil add to the
10081858SN/A# above variables
10095863Snate@binkert.orgif not GetOption('verbose'):
10101871SN/A    print "Reading SConsopts"
10111858SN/Afor bdir in [ base_dir ] + extras_dir_list:
10121858SN/A    if not isdir(bdir):
10131858SN/A        print "Error: directory '%s' does not exist" % bdir
10141858SN/A        Exit(1)
10151858SN/A    for root, dirs, files in os.walk(bdir):
10161858SN/A        if 'SConsopts' in files:
10171858SN/A            if GetOption('verbose'):
10185863Snate@binkert.org                print "Reading", joinpath(root, 'SConsopts')
10191858SN/A            SConscript(joinpath(root, 'SConsopts'))
10201858SN/A
10215863Snate@binkert.orgall_isa_list.sort()
10221859SN/A
10231859SN/Asticky_vars.AddVariables(
10241869SN/A    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
10255863Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
10265863Snate@binkert.org                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
10271869SN/A                 sorted(CpuModel.list)),
10281965SN/A    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
10297739Sgblack@eecs.umich.edu                 False),
10301965SN/A    BoolVariable('SS_COMPATIBLE_FP',
10312761Sstever@eecs.umich.edu                 'Make floating-point results compatible with SimpleScalar',
10325863Snate@binkert.org                 False),
10331869SN/A    BoolVariable('USE_SSE2',
10345863Snate@binkert.org                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
10352667Sstever@eecs.umich.edu                 False),
10361869SN/A    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
10371869SN/A    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
10382929Sktlim@umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
10392929Sktlim@umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
10405863Snate@binkert.org                  all_protocols),
10412929Sktlim@umich.edu    )
1042955SN/A
10438120Sgblack@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
10448120Sgblack@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
10458120Sgblack@eecs.umich.edu                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
10468120Sgblack@eecs.umich.edu
10478120Sgblack@eecs.umich.edu###################################################
10488120Sgblack@eecs.umich.edu#
10498120Sgblack@eecs.umich.edu# Define a SCons builder for configuration flag headers.
10508120Sgblack@eecs.umich.edu#
10518120Sgblack@eecs.umich.edu###################################################
10528120Sgblack@eecs.umich.edu
10538120Sgblack@eecs.umich.edu# This function generates a config header file that #defines the
10548120Sgblack@eecs.umich.edu# variable symbol to the current variable setting (0 or 1).  The source
1055# operands are the name of the variable and a Value node containing the
1056# value of the variable.
1057def build_config_file(target, source, env):
1058    (variable, value) = [s.get_contents() for s in source]
1059    f = file(str(target[0]), 'w')
1060    print >> f, '#define', variable, value
1061    f.close()
1062    return None
1063
1064# Combine the two functions into a scons Action object.
1065config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1066
1067# The emitter munges the source & target node lists to reflect what
1068# we're really doing.
1069def config_emitter(target, source, env):
1070    # extract variable name from Builder arg
1071    variable = str(target[0])
1072    # True target is config header file
1073    target = joinpath('config', variable.lower() + '.hh')
1074    val = env[variable]
1075    if isinstance(val, bool):
1076        # Force value to 0/1
1077        val = int(val)
1078    elif isinstance(val, str):
1079        val = '"' + val + '"'
1080
1081    # Sources are variable name & value (packaged in SCons Value nodes)
1082    return ([target], [Value(variable), Value(val)])
1083
1084config_builder = Builder(emitter = config_emitter, action = config_action)
1085
1086main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1087
1088# libelf build is shared across all configs in the build root.
1089main.SConscript('ext/libelf/SConscript',
1090                variant_dir = joinpath(build_root, 'libelf'))
1091
1092# gzstream build is shared across all configs in the build root.
1093main.SConscript('ext/gzstream/SConscript',
1094                variant_dir = joinpath(build_root, 'gzstream'))
1095
1096# libfdt build is shared across all configs in the build root.
1097main.SConscript('ext/libfdt/SConscript',
1098                variant_dir = joinpath(build_root, 'libfdt'))
1099
1100###################################################
1101#
1102# This function is used to set up a directory with switching headers
1103#
1104###################################################
1105
1106main['ALL_ISA_LIST'] = all_isa_list
1107def make_switching_dir(dname, switch_headers, env):
1108    # Generate the header.  target[0] is the full path of the output
1109    # header to generate.  'source' is a dummy variable, since we get the
1110    # list of ISAs from env['ALL_ISA_LIST'].
1111    def gen_switch_hdr(target, source, env):
1112        fname = str(target[0])
1113        f = open(fname, 'w')
1114        isa = env['TARGET_ISA'].lower()
1115        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1116        f.close()
1117
1118    # Build SCons Action object. 'varlist' specifies env vars that this
1119    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1120    # should get re-executed.
1121    switch_hdr_action = MakeAction(gen_switch_hdr,
1122                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1123
1124    # Instantiate actions for each header
1125    for hdr in switch_headers:
1126        env.Command(hdr, [], switch_hdr_action)
1127Export('make_switching_dir')
1128
1129###################################################
1130#
1131# Define build environments for selected configurations.
1132#
1133###################################################
1134
1135for variant_path in variant_paths:
1136    print "Building in", variant_path
1137
1138    # Make a copy of the build-root environment to use for this config.
1139    env = main.Clone()
1140    env['BUILDDIR'] = variant_path
1141
1142    # variant_dir is the tail component of build path, and is used to
1143    # determine the build parameters (e.g., 'ALPHA_SE')
1144    (build_root, variant_dir) = splitpath(variant_path)
1145
1146    # Set env variables according to the build directory config.
1147    sticky_vars.files = []
1148    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1149    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1150    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1151    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1152    if isfile(current_vars_file):
1153        sticky_vars.files.append(current_vars_file)
1154        print "Using saved variables file %s" % current_vars_file
1155    else:
1156        # Build dir-specific variables file doesn't exist.
1157
1158        # Make sure the directory is there so we can create it later
1159        opt_dir = dirname(current_vars_file)
1160        if not isdir(opt_dir):
1161            mkdir(opt_dir)
1162
1163        # Get default build variables from source tree.  Variables are
1164        # normally determined by name of $VARIANT_DIR, but can be
1165        # overridden by '--default=' arg on command line.
1166        default = GetOption('default')
1167        opts_dir = joinpath(main.root.abspath, 'build_opts')
1168        if default:
1169            default_vars_files = [joinpath(build_root, 'variables', default),
1170                                  joinpath(opts_dir, default)]
1171        else:
1172            default_vars_files = [joinpath(opts_dir, variant_dir)]
1173        existing_files = filter(isfile, default_vars_files)
1174        if existing_files:
1175            default_vars_file = existing_files[0]
1176            sticky_vars.files.append(default_vars_file)
1177            print "Variables file %s not found,\n  using defaults in %s" \
1178                  % (current_vars_file, default_vars_file)
1179        else:
1180            print "Error: cannot find variables file %s or " \
1181                  "default file(s) %s" \
1182                  % (current_vars_file, ' or '.join(default_vars_files))
1183            Exit(1)
1184
1185    # Apply current variable settings to env
1186    sticky_vars.Update(env)
1187
1188    help_texts["local_vars"] += \
1189        "Build variables for %s:\n" % variant_dir \
1190                 + sticky_vars.GenerateHelpText(env)
1191
1192    # Process variable settings.
1193
1194    if not have_fenv and env['USE_FENV']:
1195        print "Warning: <fenv.h> not available; " \
1196              "forcing USE_FENV to False in", variant_dir + "."
1197        env['USE_FENV'] = False
1198
1199    if not env['USE_FENV']:
1200        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1201        print "         FP results may deviate slightly from other platforms."
1202
1203    if env['EFENCE']:
1204        env.Append(LIBS=['efence'])
1205
1206    # Save sticky variable settings back to current variables file
1207    sticky_vars.Save(current_vars_file, env)
1208
1209    if env['USE_SSE2']:
1210        env.Append(CCFLAGS=['-msse2'])
1211
1212    # The src/SConscript file sets up the build rules in 'env' according
1213    # to the configured variables.  It returns a list of environments,
1214    # one for each variant build (debug, opt, etc.)
1215    envList = SConscript('src/SConscript', variant_dir = variant_path,
1216                         exports = 'env')
1217
1218    # Set up the regression tests for each build.
1219    for e in envList:
1220        SConscript('tests/SConscript',
1221                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1222                   exports = { 'env' : e }, duplicate = False)
1223
1224# base help text
1225Help('''
1226Usage: scons [scons options] [build variables] [target(s)]
1227
1228Extra scons options:
1229%(options)s
1230
1231Global build variables:
1232%(global_vars)s
1233
1234%(local_vars)s
1235''' % help_texts)
1236