SConstruct revision 9477
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
4955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
5955SN/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
282665Ssaidi@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
292665Ssaidi@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30955SN/A#
31955SN/A# Authors: Steve Reinhardt
32955SN/A#          Nathan Binkert
33955SN/A
34955SN/A###################################################
352632Sstever@eecs.umich.edu#
362632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
372632Sstever@eecs.umich.edu#
382632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
39955SN/A# 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).
422761Sstever@eecs.umich.edu#
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
452632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
462761Sstever@eecs.umich.edu# built for the same host system.
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# Examples:
492632Sstever@eecs.umich.edu#
502632Sstever@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.
522761Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
532761Sstever@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
562632Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
572632Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
582632Sstever@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
63955SN/A# 'gem5' directory (or use -u or -C to tell scons where to find this
64955SN/A# file), you can use 'scons -h' to print all the gem5-specific build
65955SN/A# options as well.
66955SN/A#
67955SN/A###################################################
685396Ssaidi@eecs.umich.edu
694202Sbinkertn@umich.edu# Check for recent-enough Python and SCons versions.
705342Sstever@gmail.comtry:
71955SN/A    # Really old versions of scons only take two options for the
725273Sstever@gmail.com    # function, so check once without the revision and once with the
735273Sstever@gmail.com    # revision, the first instance will fail for stuff other than
742656Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
752656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
762656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
772656Sstever@eecs.umich.eduexcept SystemExit, e:
782656Sstever@eecs.umich.edu    print """
792656Sstever@eecs.umich.eduFor more details, see:
802656Sstever@eecs.umich.edu    http://gem5.org/Dependencies
812653Sstever@eecs.umich.edu"""
825227Ssaidi@eecs.umich.edu    raise
835227Ssaidi@eecs.umich.edu
845227Ssaidi@eecs.umich.edu# We ensure the python version early because we have stuff that
855227Ssaidi@eecs.umich.edu# requires python 2.4
865396Ssaidi@eecs.umich.edutry:
875396Ssaidi@eecs.umich.edu    EnsurePythonVersion(2, 4)
885396Ssaidi@eecs.umich.eduexcept SystemExit, e:
895396Ssaidi@eecs.umich.edu    print """
905396Ssaidi@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
915396Ssaidi@eecs.umich.edueither (1) rearranging your PATH so that scons finds the non-default
925396Ssaidi@eecs.umich.edu'python' first or (2) explicitly invoking an alternative interpreter
935396Ssaidi@eecs.umich.eduon the scons script.
945396Ssaidi@eecs.umich.edu
955396Ssaidi@eecs.umich.eduFor more details, see:
965396Ssaidi@eecs.umich.edu    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
975396Ssaidi@eecs.umich.edu"""
985396Ssaidi@eecs.umich.edu    raise
995396Ssaidi@eecs.umich.edu
1005396Ssaidi@eecs.umich.edu# Global Python includes
1015396Ssaidi@eecs.umich.eduimport os
1025396Ssaidi@eecs.umich.eduimport re
1035396Ssaidi@eecs.umich.eduimport subprocess
1045396Ssaidi@eecs.umich.eduimport sys
1055396Ssaidi@eecs.umich.edu
1065396Ssaidi@eecs.umich.edufrom os import mkdir, environ
1075396Ssaidi@eecs.umich.edufrom os.path import abspath, basename, dirname, expanduser, normpath
1085396Ssaidi@eecs.umich.edufrom os.path import exists,  isdir, isfile
1095396Ssaidi@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
1105396Ssaidi@eecs.umich.edu
1115396Ssaidi@eecs.umich.edu# SCons includes
1125396Ssaidi@eecs.umich.eduimport SCons
1135396Ssaidi@eecs.umich.eduimport SCons.Node
1145396Ssaidi@eecs.umich.edu
1155396Ssaidi@eecs.umich.eduextra_python_paths = [
1165396Ssaidi@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1175396Ssaidi@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1185396Ssaidi@eecs.umich.edu    ]
1195396Ssaidi@eecs.umich.edu
1205396Ssaidi@eecs.umich.edusys.path[1:1] = extra_python_paths
1215396Ssaidi@eecs.umich.edu
1225396Ssaidi@eecs.umich.edufrom m5.util import compareVersions, readCommand
1235396Ssaidi@eecs.umich.edufrom m5.util.terminal import get_termcap
1245396Ssaidi@eecs.umich.edu
1255396Ssaidi@eecs.umich.eduhelp_texts = {
1265396Ssaidi@eecs.umich.edu    "options" : "",
1275396Ssaidi@eecs.umich.edu    "global_vars" : "",
1285396Ssaidi@eecs.umich.edu    "local_vars" : ""
1295396Ssaidi@eecs.umich.edu}
1305396Ssaidi@eecs.umich.edu
1315396Ssaidi@eecs.umich.eduExport("help_texts")
1325396Ssaidi@eecs.umich.edu
1335396Ssaidi@eecs.umich.edu
1345396Ssaidi@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1355396Ssaidi@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1365396Ssaidi@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1375396Ssaidi@eecs.umich.edu# Help() function, but these two features are incompatible: once
1385396Ssaidi@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1395396Ssaidi@eecs.umich.edu# at the help texts from AddOptions.  See:
1405396Ssaidi@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1415396Ssaidi@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1425396Ssaidi@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1435396Ssaidi@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1445396Ssaidi@eecs.umich.edu# we can just use AddOption directly.
1455396Ssaidi@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1465396Ssaidi@eecs.umich.edu    col_width = 30
1475396Ssaidi@eecs.umich.edu
1485396Ssaidi@eecs.umich.edu    help = "  " + ", ".join(args)
1495396Ssaidi@eecs.umich.edu    if "help" in kwargs:
1504781Snate@binkert.org        length = len(help)
1511852SN/A        if length >= col_width:
152955SN/A            help += "\n" + " " * col_width
153955SN/A        else:
154955SN/A            help += " " * (col_width - length)
1553717Sstever@eecs.umich.edu        help += kwargs["help"]
1563716Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
157955SN/A
1581533SN/A    AddOption(*args, **kwargs)
1593716Sstever@eecs.umich.edu
1601533SN/AAddLocalOption('--colors', dest='use_colors', action='store_true',
1614678Snate@binkert.org               help="Add color to abbreviated scons output")
1624678Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1634678Snate@binkert.org               help="Don't add color to abbreviated scons output")
1644678Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1654678Snate@binkert.org               help='Override which build_opts file to use for defaults')
1664678Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1674678Snate@binkert.org               help='Disable style checking hooks')
1684678Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1694678Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1704678Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1714678Snate@binkert.org               help='Update test reference outputs')
1724678Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1734678Snate@binkert.org               help='Print full tool command lines')
1744678Snate@binkert.org
1754678Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1764678Snate@binkert.org
1774678Snate@binkert.org########################################################################
1784678Snate@binkert.org#
1794678Snate@binkert.org# Set up the main build environment.
1804678Snate@binkert.org#
1814678Snate@binkert.org########################################################################
1824973Ssaidi@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1834678Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1844678Snate@binkert.org                 'RANLIB', 'SWIG' ])
1854678Snate@binkert.org
1864678Snate@binkert.orguse_prefixes = [
1874678Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
1884678Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
189955SN/A    "CCACHE_",      # ccache (caching compiler wrapper) configuration
190955SN/A    "CCC_",         # clang static analyzer configuration
1912632Sstever@eecs.umich.edu    ]
1922632Sstever@eecs.umich.edu
193955SN/Ause_env = {}
194955SN/Afor key,val in os.environ.iteritems():
195955SN/A    if key in use_vars or \
196955SN/A            any([key.startswith(prefix) for prefix in use_prefixes]):
1972632Sstever@eecs.umich.edu        use_env[key] = val
198955SN/A
1992632Sstever@eecs.umich.edumain = Environment(ENV=use_env)
2002632Sstever@eecs.umich.edumain.Decider('MD5-timestamp')
2012632Sstever@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
2022632Sstever@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2032632Sstever@eecs.umich.edu
2042632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2052632Sstever@eecs.umich.edu
2062632Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
2072632Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2082632Sstever@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2092632Sstever@eecs.umich.edu    Exit(1)
2102632Sstever@eecs.umich.edu
2112632Sstever@eecs.umich.edu# Check that swig is present
2123718Sstever@eecs.umich.eduif not 'SWIG' in main_dict_keys:
2133718Sstever@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2143718Sstever@eecs.umich.edu    Exit(1)
2153718Sstever@eecs.umich.edu
2163718Sstever@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2173718Sstever@eecs.umich.edu# as well
2183718Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2193718Sstever@eecs.umich.edu
2203718Sstever@eecs.umich.edu########################################################################
2213718Sstever@eecs.umich.edu#
2223718Sstever@eecs.umich.edu# Mercurial Stuff.
2233718Sstever@eecs.umich.edu#
2243718Sstever@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2252634Sstever@eecs.umich.edu# extra things.
2262634Sstever@eecs.umich.edu#
2272632Sstever@eecs.umich.edu########################################################################
2282638Sstever@eecs.umich.edu
2292632Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2302632Sstever@eecs.umich.edu
2312632Sstever@eecs.umich.edumercurial_style_message = """
2322632Sstever@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2332632Sstever@eecs.umich.eduagainst the gem5 style rules on hg commit and qrefresh commands.  This
2342632Sstever@eecs.umich.eduscript will now install the hook in your .hg/hgrc file.
2351858SN/APress enter to continue, or ctrl-c to abort: """
2363716Sstever@eecs.umich.edu
2372638Sstever@eecs.umich.edumercurial_style_hook = """
2382638Sstever@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2392638Sstever@eecs.umich.edu# to provide the gem5 style-checking hooks
2402638Sstever@eecs.umich.edu[extensions]
2412638Sstever@eecs.umich.edustyle = %s/util/style.py
2422638Sstever@eecs.umich.edu
2432638Sstever@eecs.umich.edu[hooks]
2443716Sstever@eecs.umich.edupretxncommit.style = python:style.check_style
2452634Sstever@eecs.umich.edupre-qrefresh.style = python:style.check_style
2462634Sstever@eecs.umich.edu# End of SConstruct additions
247955SN/A
2485341Sstever@gmail.com""" % (main.root.abspath)
2495341Sstever@gmail.com
2505341Sstever@gmail.commercurial_lib_not_found = """
2515341Sstever@gmail.comMercurial libraries cannot be found, ignoring style hook.  If
252955SN/Ayou are a gem5 developer, please fix this and run the style
253955SN/Ahook. It is important.
254955SN/A"""
255955SN/A
256955SN/A# Check for style hook and prompt for installation if it's not there.
257955SN/A# Skip this if --ignore-style was specified, there's no .hg dir to
258955SN/A# install a hook in, or there's no interactive terminal to prompt.
2591858SN/Aif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2601858SN/A    style_hook = True
2612632Sstever@eecs.umich.edu    try:
262955SN/A        from mercurial import ui
2634494Ssaidi@eecs.umich.edu        ui = ui.ui()
2644494Ssaidi@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2653716Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2661105SN/A                     ui.config('hooks', 'pre-qrefresh.style', None)
2672667Sstever@eecs.umich.edu    except ImportError:
2682667Sstever@eecs.umich.edu        print mercurial_lib_not_found
2692667Sstever@eecs.umich.edu
2702667Sstever@eecs.umich.edu    if not style_hook:
2712667Sstever@eecs.umich.edu        print mercurial_style_message,
2722667Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
2731869SN/A        try:
2741869SN/A            raw_input()
2751869SN/A        except:
2761869SN/A            print "Input exception, exiting scons.\n"
2771869SN/A            sys.exit(1)
2781065SN/A        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2795341Sstever@gmail.com        print "Adding style hook to", hgrc_path, "\n"
2805341Sstever@gmail.com        try:
2815341Sstever@gmail.com            hgrc = open(hgrc_path, 'a')
2825341Sstever@gmail.com            hgrc.write(mercurial_style_hook)
2835341Sstever@gmail.com            hgrc.close()
2845341Sstever@gmail.com        except:
2855341Sstever@gmail.com            print "Error updating", hgrc_path
2865341Sstever@gmail.com            sys.exit(1)
2875341Sstever@gmail.com
2885341Sstever@gmail.com
2895341Sstever@gmail.com###################################################
2905341Sstever@gmail.com#
2915341Sstever@gmail.com# Figure out which configurations to set up based on the path(s) of
2925341Sstever@gmail.com# the target(s).
2935341Sstever@gmail.com#
2945341Sstever@gmail.com###################################################
2955341Sstever@gmail.com
2965341Sstever@gmail.com# Find default configuration & binary.
2975341Sstever@gmail.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2985341Sstever@gmail.com
2995341Sstever@gmail.com# helper function: find last occurrence of element in list
3005341Sstever@gmail.comdef rfind(l, elt, offs = -1):
3015341Sstever@gmail.com    for i in range(len(l)+offs, 0, -1):
3025341Sstever@gmail.com        if l[i] == elt:
3035341Sstever@gmail.com            return i
3045341Sstever@gmail.com    raise ValueError, "element not found"
3055341Sstever@gmail.com
3065397Ssaidi@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3075397Ssaidi@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
3085341Sstever@gmail.com# relative to the launch directory unless a different root is provided
3095341Sstever@gmail.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3105341Sstever@gmail.com    return [abspath(joinpath(root, expanduser(str(p))))
3115341Sstever@gmail.com            for p in path_list]
3125341Sstever@gmail.com
3135341Sstever@gmail.com# Each target must have 'build' in the interior of the path; the
3145341Sstever@gmail.com# directory below this will determine the build parameters.  For
3155341Sstever@gmail.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3165341Sstever@gmail.com# recognize that ALPHA_SE specifies the configuration because it
3175341Sstever@gmail.com# follow 'build' in the build path.
3185341Sstever@gmail.com
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
3215341Sstever@gmail.com# doesn't work (obviously!).
3225341Sstever@gmail.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3235341Sstever@gmail.com
3245341Sstever@gmail.com# Generate a list of the unique build roots and configs that the
3255341Sstever@gmail.com# collected targets reference.
3265341Sstever@gmail.comvariant_paths = []
3275341Sstever@gmail.combuild_root = None
3285341Sstever@gmail.comfor t in BUILD_TARGETS:
3295341Sstever@gmail.com    path_dirs = t.split('/')
3305344Sstever@gmail.com    try:
3315341Sstever@gmail.com        build_top = rfind(path_dirs, 'build', -2)
3325341Sstever@gmail.com    except:
3335341Sstever@gmail.com        print "Error: no non-leaf 'build' dir found on target path", t
3345341Sstever@gmail.com        Exit(1)
3355341Sstever@gmail.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3362632Sstever@eecs.umich.edu    if not build_root:
3375199Sstever@gmail.com        build_root = this_build_root
3383918Ssaidi@eecs.umich.edu    else:
3393918Ssaidi@eecs.umich.edu        if this_build_root != build_root:
3403940Ssaidi@eecs.umich.edu            print "Error: build targets not under same build root\n"\
3414781Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3424781Snate@binkert.org            Exit(1)
3433918Ssaidi@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3444781Snate@binkert.org    if variant_path not in variant_paths:
3454781Snate@binkert.org        variant_paths.append(variant_path)
3463918Ssaidi@eecs.umich.edu
3474781Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
3484781Snate@binkert.orgif not isdir(build_root):
3493940Ssaidi@eecs.umich.edu    mkdir(build_root)
3503942Ssaidi@eecs.umich.edumain['BUILDROOT'] = build_root
3513940Ssaidi@eecs.umich.edu
3523918Ssaidi@eecs.umich.eduExport('main')
3533918Ssaidi@eecs.umich.edu
354955SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
3551858SN/A
3563918Ssaidi@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
3573918Ssaidi@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3583918Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3593918Ssaidi@eecs.umich.edu# (soft) links work better.
3603940Ssaidi@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
3613940Ssaidi@eecs.umich.edu
3623918Ssaidi@eecs.umich.edu#
3633918Ssaidi@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
3643918Ssaidi@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
3653918Ssaidi@eecs.umich.edu#
3663918Ssaidi@eecs.umich.edu
3673918Ssaidi@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3683918Ssaidi@eecs.umich.edu
3693918Ssaidi@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3703918Ssaidi@eecs.umich.edu
3713940Ssaidi@eecs.umich.eduglobal_vars.AddVariables(
3723918Ssaidi@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3733918Ssaidi@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3745397Ssaidi@eecs.umich.edu    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3755397Ssaidi@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3765397Ssaidi@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
3775397Ssaidi@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3785397Ssaidi@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3795397Ssaidi@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
3801851SN/A    )
3811851SN/A
3821858SN/A# Update main environment with values from ARGUMENTS & global_vars_file
3835200Sstever@gmail.comglobal_vars.Update(main)
384955SN/Ahelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3853053Sstever@eecs.umich.edu
3863053Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
3873053Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
3883053Sstever@eecs.umich.edu
3893053Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
3903053Sstever@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
3913053Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
3923053Sstever@eecs.umich.eduif main['EXTRAS']:
3933053Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3944742Sstever@eecs.umich.eduelse:
3954742Sstever@eecs.umich.edu    extras_dir_list = []
3963053Sstever@eecs.umich.edu
3973053Sstever@eecs.umich.eduExport('base_dir')
3983053Sstever@eecs.umich.eduExport('extras_dir_list')
3993053Sstever@eecs.umich.edu
4003053Sstever@eecs.umich.edu# the ext directory should be on the #includes path
4013053Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
4023053Sstever@eecs.umich.edu
4033053Sstever@eecs.umich.edudef strip_build_path(path, env):
4043053Sstever@eecs.umich.edu    path = str(path)
4052667Sstever@eecs.umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
4064554Sbinkertn@umich.edu    if path.startswith(variant_base):
4074554Sbinkertn@umich.edu        path = path[len(variant_base):]
4082667Sstever@eecs.umich.edu    elif path.startswith('build/'):
4094554Sbinkertn@umich.edu        path = path[6:]
4104554Sbinkertn@umich.edu    return path
4114554Sbinkertn@umich.edu
4124554Sbinkertn@umich.edu# Generate a string of the form:
4134554Sbinkertn@umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
4144554Sbinkertn@umich.edu# to print while building.
4154554Sbinkertn@umich.educlass Transform(object):
4164781Snate@binkert.org    # all specific color settings should be here and nowhere else
4174554Sbinkertn@umich.edu    tool_color = termcap.Normal
4184554Sbinkertn@umich.edu    pfx_color = termcap.Yellow
4192667Sstever@eecs.umich.edu    srcs_color = termcap.Yellow + termcap.Bold
4204554Sbinkertn@umich.edu    arrow_color = termcap.Blue + termcap.Bold
4214554Sbinkertn@umich.edu    tgts_color = termcap.Yellow + termcap.Bold
4224554Sbinkertn@umich.edu
4234554Sbinkertn@umich.edu    def __init__(self, tool, max_sources=99):
4242667Sstever@eecs.umich.edu        self.format = self.tool_color + (" [%8s] " % tool) \
4254554Sbinkertn@umich.edu                      + self.pfx_color + "%s" \
4262667Sstever@eecs.umich.edu                      + self.srcs_color + "%s" \
4274554Sbinkertn@umich.edu                      + self.arrow_color + " -> " \
4284554Sbinkertn@umich.edu                      + self.tgts_color + "%s" \
4292667Sstever@eecs.umich.edu                      + termcap.Normal
4302638Sstever@eecs.umich.edu        self.max_sources = max_sources
4312638Sstever@eecs.umich.edu
4322638Sstever@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
4333716Sstever@eecs.umich.edu        # truncate source list according to max_sources param
4343716Sstever@eecs.umich.edu        source = source[0:self.max_sources]
4351858SN/A        def strip(f):
4365227Ssaidi@eecs.umich.edu            return strip_build_path(str(f), env)
4375227Ssaidi@eecs.umich.edu        if len(source) > 0:
4385227Ssaidi@eecs.umich.edu            srcs = map(strip, source)
4395227Ssaidi@eecs.umich.edu        else:
4405227Ssaidi@eecs.umich.edu            srcs = ['']
4415227Ssaidi@eecs.umich.edu        tgts = map(strip, target)
4425227Ssaidi@eecs.umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4435227Ssaidi@eecs.umich.edu        # operation that has nothing to do with paths.
4445227Ssaidi@eecs.umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
4455227Ssaidi@eecs.umich.edu        com_pfx_len = len(com_pfx)
4465227Ssaidi@eecs.umich.edu        if com_pfx:
4475227Ssaidi@eecs.umich.edu            # do some cleanup and sanity checking on common prefix
4485227Ssaidi@eecs.umich.edu            if com_pfx[-1] == ".":
4495227Ssaidi@eecs.umich.edu                # prefix matches all but file extension: ok
4505227Ssaidi@eecs.umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4515204Sstever@gmail.com                com_pfx = com_pfx[0:-1]
4525204Sstever@gmail.com            elif com_pfx[-1] == "/":
4535204Sstever@gmail.com                # common prefix is directory path: OK
4545204Sstever@gmail.com                pass
4555204Sstever@gmail.com            else:
4565204Sstever@gmail.com                src0_len = len(srcs[0])
4575204Sstever@gmail.com                tgt0_len = len(tgts[0])
4585204Sstever@gmail.com                if src0_len == com_pfx_len:
4595204Sstever@gmail.com                    # source is a substring of target, OK
4605204Sstever@gmail.com                    pass
4615204Sstever@gmail.com                elif tgt0_len == com_pfx_len:
4625204Sstever@gmail.com                    # target is a substring of source, need to back up to
4635204Sstever@gmail.com                    # avoid empty string on RHS of arrow
4645204Sstever@gmail.com                    sep_idx = com_pfx.rfind(".")
4655204Sstever@gmail.com                    if sep_idx != -1:
4665204Sstever@gmail.com                        com_pfx = com_pfx[0:sep_idx]
4675204Sstever@gmail.com                    else:
4685204Sstever@gmail.com                        com_pfx = ''
4695204Sstever@gmail.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4703118Sstever@eecs.umich.edu                    # still splitting at file extension: ok
4713118Sstever@eecs.umich.edu                    pass
4723118Sstever@eecs.umich.edu                else:
4733118Sstever@eecs.umich.edu                    # probably a fluke; ignore it
4743118Sstever@eecs.umich.edu                    com_pfx = ''
4753118Sstever@eecs.umich.edu        # recalculate length in case com_pfx was modified
4763118Sstever@eecs.umich.edu        com_pfx_len = len(com_pfx)
4773118Sstever@eecs.umich.edu        def fmt(files):
4783118Sstever@eecs.umich.edu            f = map(lambda s: s[com_pfx_len:], files)
4793118Sstever@eecs.umich.edu            return ', '.join(f)
4803118Sstever@eecs.umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4813716Sstever@eecs.umich.edu
4823118Sstever@eecs.umich.eduExport('Transform')
4833118Sstever@eecs.umich.edu
4843118Sstever@eecs.umich.edu# enable the regression script to use the termcap
4853118Sstever@eecs.umich.edumain['TERMCAP'] = termcap
4863118Sstever@eecs.umich.edu
4873118Sstever@eecs.umich.eduif GetOption('verbose'):
4883118Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
4893118Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
4903118Sstever@eecs.umich.eduelse:
4913716Sstever@eecs.umich.edu    MakeAction = Action
4923118Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
4933118Sstever@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
4943118Sstever@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
4953118Sstever@eecs.umich.edu    main['SWIGCOMSTR']      = Transform("SWIG")
4963118Sstever@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
4973118Sstever@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
4983118Sstever@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4993118Sstever@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
5003118Sstever@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
5013118Sstever@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
5023483Ssaidi@eecs.umich.eduExport('MakeAction')
5033494Ssaidi@eecs.umich.edu
5043494Ssaidi@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
5053483Ssaidi@eecs.umich.edumain['LTO_CCFLAGS'] = []
5063483Ssaidi@eecs.umich.edumain['LTO_LDFLAGS'] = []
5073483Ssaidi@eecs.umich.edu
5083053Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5093053Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5103918Ssaidi@eecs.umich.edu
5113053Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5123053Sstever@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5133053Sstever@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
5143053Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
5153053Sstever@eecs.umich.edu    Exit(1)
5161858SN/A
5171858SN/A# Set up default C++ compiler flags
5181858SN/Aif main['GCC']:
5191858SN/A    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5201858SN/A    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5211858SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5221859SN/A    if compareVersions(gcc_version, "4.4") < 0:
5231858SN/A        print 'Error: gcc version 4.4 or newer required.'
5241858SN/A        print '       Installed version:', gcc_version
5251858SN/A        Exit(1)
5261859SN/A
5271859SN/A    main['GCC_VERSION'] = gcc_version
5281862SN/A    main.Append(CCFLAGS=['-pipe'])
5293053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5303053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5313053Sstever@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++0x'])
5323053Sstever@eecs.umich.edu
5331859SN/A    # Check for versions with bugs
5341859SN/A    if not compareVersions(gcc_version, '4.4.1') or \
5351859SN/A       not compareVersions(gcc_version, '4.4.2'):
5361859SN/A        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5371859SN/A        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5381859SN/A
5391859SN/A    # LTO support is only really working properly from 4.6 and beyond
5401859SN/A    if compareVersions(gcc_version, '4.6') >= 0:
5411862SN/A        # Add the appropriate Link-Time Optimization (LTO) flags
5421859SN/A        # unless LTO is explicitly turned off. Note that these flags
5431859SN/A        # are only used by the fast target.
5441859SN/A        if not GetOption('no_lto'):
5451858SN/A            # Pass the LTO flag when compiling to produce GIMPLE
5461858SN/A            # output, we merely create the flags here and only append
5472139SN/A            # them later/
5484202Sbinkertn@umich.edu            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5494202Sbinkertn@umich.edu
5502139SN/A            # Use the same amount of jobs for LTO as we are running
5512155SN/A            # scons with, we hardcode the use of the linker plugin
5524202Sbinkertn@umich.edu            # which requires either gold or GNU ld >= 2.21
5534202Sbinkertn@umich.edu            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5544202Sbinkertn@umich.edu                                   '-fuse-linker-plugin']
5552155SN/A
5561869SN/Aelif main['CLANG']:
5571869SN/A    # Check for a supported version of clang, >= 2.9 is needed to
5581869SN/A    # support similar features as gcc 4.4. See
5591869SN/A    # http://clang.llvm.org/cxx_status.html for details
5604202Sbinkertn@umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
5614202Sbinkertn@umich.edu    clang_version_match = clang_version_re.match(CXX_version)
5624202Sbinkertn@umich.edu    if (clang_version_match):
5634202Sbinkertn@umich.edu        clang_version = clang_version_match.groups()[0]
5644202Sbinkertn@umich.edu        if compareVersions(clang_version, "2.9") < 0:
5654202Sbinkertn@umich.edu            print 'Error: clang version 2.9 or newer required.'
5664202Sbinkertn@umich.edu            print '       Installed version:', clang_version
5674202Sbinkertn@umich.edu            Exit(1)
5685341Sstever@gmail.com    else:
5695341Sstever@gmail.com        print 'Error: Unable to determine clang version.'
5705341Sstever@gmail.com        Exit(1)
5715342Sstever@gmail.com
5725342Sstever@gmail.com    main.Append(CCFLAGS=['-pipe'])
5734202Sbinkertn@umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5744202Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5754202Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Wno-tautological-compare'])
5764202Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Wno-self-assign'])
5774202Sbinkertn@umich.edu    # Ruby makes frequent use of extraneous parantheses in the printing
5781869SN/A    # of if-statements
5794202Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Wno-parentheses'])
5801869SN/A    main.Append(CXXFLAGS=['-std=c++0x'])
5812508SN/A    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5822508SN/A    # opposed to libstdc++ to make the transition from TR1 to
5832508SN/A    # C++11. See http://libcxx.llvm.org. However, clang has chosen a
5842508SN/A    # strict implementation of the C++11 standard, and does not allow
5854202Sbinkertn@umich.edu    # incomplete types in template arguments (besides unique_ptr and
5861869SN/A    # shared_ptr), and the libc++ STL containers create problems in
5875385Sstever@gmail.com    # combination with the current gem5 code. For now, we stick with
5885385Sstever@gmail.com    # libstdc++ and use the TR1 namespace.
5895385Sstever@gmail.com    # if sys.platform == "darwin":
5905385Sstever@gmail.com    #     main.Append(CXXFLAGS=['-stdlib=libc++'])
5911869SN/A
5921869SN/Aelse:
5931869SN/A    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5941869SN/A    print "Don't know what compiler options to use for your compiler."
5951869SN/A    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5961965SN/A    print termcap.Yellow + '       version:' + termcap.Normal,
5971965SN/A    if not CXX_version:
5981965SN/A        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5991869SN/A               termcap.Normal
6001869SN/A    else:
6012733Sktlim@umich.edu        print CXX_version.replace('\n', '<nl>')
6023356Sbinkertn@umich.edu    print "       If you're trying to use a compiler other than GCC"
6033356Sbinkertn@umich.edu    print "       or clang, there appears to be something wrong with your"
6044773Snate@binkert.org    print "       environment."
6051869SN/A    print "       "
6061858SN/A    print "       If you are trying to use a compiler other than those listed"
6071869SN/A    print "       above you will need to ease fix SConstruct and "
6081869SN/A    print "       src/SConscript to support that compiler."
6091869SN/A    Exit(1)
6101858SN/A
6112761Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
6121869SN/Amain['YACCFLAGS'] = '-d'
6135385Sstever@gmail.commain['YACCHXXFILESUFFIX'] = '.hh'
6145385Sstever@gmail.com
6153584Ssaidi@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
6161869SN/A# extra 'qdo' every time we run scons.
6171869SN/Aif main['BATCH']:
6181869SN/A    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6191869SN/A    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6201869SN/A    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6211869SN/A    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6221858SN/A    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
623955SN/A
624955SN/Aif sys.platform == 'cygwin':
6251869SN/A    # cygwin has some header file issues...
6261869SN/A    main.Append(CCFLAGS=["-Wno-uninitialized"])
6271869SN/A
6281869SN/A# Check for the protobuf compiler
6291869SN/Aprotoc_version = readCommand([main['PROTOC'], '--version'],
6301869SN/A                             exception='').split()
6311869SN/A
6321869SN/A# First two words should be "libprotoc x.y.z"
6331869SN/Aif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6341869SN/A    print termcap.Yellow + termcap.Bold + \
6351869SN/A        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6361869SN/A        '         Please install protobuf-compiler for tracing support.' + \
6371869SN/A        termcap.Normal
6381869SN/A    main['PROTOC'] = False
6391869SN/Aelse:
6401869SN/A    # Based on the availability of the compress stream wrappers,
6411869SN/A    # require 2.1.0
6421869SN/A    min_protoc_version = '2.1.0'
6431869SN/A    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6441869SN/A        print termcap.Yellow + termcap.Bold + \
6451869SN/A            'Warning: protoc version', min_protoc_version, \
6461869SN/A            'or newer required.\n' + \
6471869SN/A            '         Installed version:', protoc_version[1], \
6481869SN/A            termcap.Normal
6491869SN/A        main['PROTOC'] = False
6501869SN/A    else:
6511869SN/A        # Attempt to determine the appropriate include path and
6521869SN/A        # library path using pkg-config, that means we also need to
6531869SN/A        # check for pkg-config. Note that it is possible to use
6543716Sstever@eecs.umich.edu        # protobuf without the involvement of pkg-config. Later on we
6553356Sbinkertn@umich.edu        # check go a library config check and at that point the test
6563356Sbinkertn@umich.edu        # will fail if libprotobuf cannot be found.
6573356Sbinkertn@umich.edu        if readCommand(['pkg-config', '--version'], exception=''):
6583356Sbinkertn@umich.edu            try:
6593356Sbinkertn@umich.edu                # Attempt to establish what linking flags to add for protobuf
6603356Sbinkertn@umich.edu                # using pkg-config
6614781Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6621869SN/A            except:
6631869SN/A                print termcap.Yellow + termcap.Bold + \
6641869SN/A                    'Warning: pkg-config could not get protobuf flags.' + \
6651869SN/A                    termcap.Normal
6661869SN/A
6671869SN/A# Check for SWIG
6681869SN/Aif not main.has_key('SWIG'):
6692655Sstever@eecs.umich.edu    print 'Error: SWIG utility not found.'
6702655Sstever@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
6712655Sstever@eecs.umich.edu    Exit(1)
6722655Sstever@eecs.umich.edu
6732655Sstever@eecs.umich.edu# Check for appropriate SWIG version
6742655Sstever@eecs.umich.eduswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
6752655Sstever@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
6762655Sstever@eecs.umich.eduif len(swig_version) < 3 or \
6772655Sstever@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
6782655Sstever@eecs.umich.edu    print 'Error determining SWIG version.'
6792655Sstever@eecs.umich.edu    Exit(1)
6802655Sstever@eecs.umich.edu
6812655Sstever@eecs.umich.edumin_swig_version = '1.3.34'
6822655Sstever@eecs.umich.eduif compareVersions(swig_version[2], min_swig_version) < 0:
6832655Sstever@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
6842655Sstever@eecs.umich.edu    print '       Installed version:', swig_version[2]
6852655Sstever@eecs.umich.edu    Exit(1)
6862655Sstever@eecs.umich.edu
6872655Sstever@eecs.umich.edu# Set up SWIG flags & scanner
6882655Sstever@eecs.umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
6892655Sstever@eecs.umich.edumain.Append(SWIGFLAGS=swig_flags)
6902655Sstever@eecs.umich.edu
6912655Sstever@eecs.umich.edu# filter out all existing swig scanners, they mess up the dependency
6922655Sstever@eecs.umich.edu# stuff for some reason
6932655Sstever@eecs.umich.eduscanners = []
6942655Sstever@eecs.umich.edufor scanner in main['SCANNERS']:
6952638Sstever@eecs.umich.edu    skeys = scanner.skeys
6962638Sstever@eecs.umich.edu    if skeys == '.i':
6973716Sstever@eecs.umich.edu        continue
6982638Sstever@eecs.umich.edu
6992638Sstever@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7001869SN/A        continue
7011869SN/A
7023546Sgblack@eecs.umich.edu    scanners.append(scanner)
7033546Sgblack@eecs.umich.edu
7043546Sgblack@eecs.umich.edu# add the new swig scanner that we like better
7053546Sgblack@eecs.umich.edufrom SCons.Scanner import ClassicCPP as CPPScanner
7064202Sbinkertn@umich.eduswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7073546Sgblack@eecs.umich.eduscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7083546Sgblack@eecs.umich.edu
7093546Sgblack@eecs.umich.edu# replace the scanners list that has what we want
7103546Sgblack@eecs.umich.edumain['SCANNERS'] = scanners
7113546Sgblack@eecs.umich.edu
7124781Snate@binkert.org# Add a custom Check function to the Configure context so that we can
7134781Snate@binkert.org# figure out if the compiler adds leading underscores to global
7144781Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
7154781Snate@binkert.org# use for embedding the python code.
7164781Snate@binkert.orgdef CheckLeading(context):
7174781Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
7184781Snate@binkert.org    # 1) Define a global variable called x from asm so the C compiler
7194781Snate@binkert.org    #    won't change the symbol at all.
7204781Snate@binkert.org    # 2) Declare that variable.
7214781Snate@binkert.org    # 3) Use the variable
7224781Snate@binkert.org    #
7234781Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
7243546Sgblack@eecs.umich.edu    # link because the external symbol 'x' will be called '_x' which
7253546Sgblack@eecs.umich.edu    # was defined by the asm statement.  If the compiler does not
7263546Sgblack@eecs.umich.edu    # prepend an underscore, this will not successfully link because
7274781Snate@binkert.org    # '_x' will have been defined by assembly, while the C portion of
7283546Sgblack@eecs.umich.edu    # the code will be trying to use 'x'
7293546Sgblack@eecs.umich.edu    ret = context.TryLink('''
7303546Sgblack@eecs.umich.edu        asm(".globl _x; _x: .byte 0");
7313546Sgblack@eecs.umich.edu        extern int x;
7323546Sgblack@eecs.umich.edu        int main() { return x; }
7333546Sgblack@eecs.umich.edu        ''', extension=".c")
7343546Sgblack@eecs.umich.edu    context.env.Append(LEADING_UNDERSCORE=ret)
7353546Sgblack@eecs.umich.edu    context.Result(ret)
7363546Sgblack@eecs.umich.edu    return ret
7373546Sgblack@eecs.umich.edu
7384202Sbinkertn@umich.edu# Platform-specific configuration.  Note again that we assume that all
7393546Sgblack@eecs.umich.edu# builds under a given build root run on the same host platform.
7403546Sgblack@eecs.umich.educonf = Configure(main,
7413546Sgblack@eecs.umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
742955SN/A                 log_file = joinpath(build_root, 'scons_config.log'),
743955SN/A                 custom_tests = { 'CheckLeading' : CheckLeading })
744955SN/A
745955SN/A# Check for leading underscores.  Don't really need to worry either
7461858SN/A# way so don't need to check the return code.
7471858SN/Aconf.CheckLeading()
7481858SN/A
7492632Sstever@eecs.umich.edu# Check if we should compile a 64 bit binary on Mac OS X/Darwin
7502632Sstever@eecs.umich.edutry:
7515343Sstever@gmail.com    import platform
7525343Sstever@gmail.com    uname = platform.uname()
7535343Sstever@gmail.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
7544773Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
7554773Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
7562632Sstever@eecs.umich.edu            main.Append(CFLAGS=['-arch', 'x86_64'])
7572632Sstever@eecs.umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
7582632Sstever@eecs.umich.edu            main.Append(ASFLAGS=['-arch', 'x86_64'])
7592023SN/Aexcept:
7602632Sstever@eecs.umich.edu    pass
7612632Sstever@eecs.umich.edu
7622632Sstever@eecs.umich.edu# Recent versions of scons substitute a "Null" object for Configure()
7632632Sstever@eecs.umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
7642632Sstever@eecs.umich.edu# present.  Unfortuantely this Null object always returns false,
7653716Sstever@eecs.umich.edu# breaking all our configuration checks.  We replace it with our own
7665342Sstever@gmail.com# more optimistic null object that returns True instead.
7672632Sstever@eecs.umich.eduif not conf:
7682632Sstever@eecs.umich.edu    def NullCheck(*args, **kwargs):
7692632Sstever@eecs.umich.edu        return True
7702632Sstever@eecs.umich.edu
7712023SN/A    class NullConf:
7722632Sstever@eecs.umich.edu        def __init__(self, env):
7732632Sstever@eecs.umich.edu            self.env = env
7745342Sstever@gmail.com        def Finish(self):
7751889SN/A            return self.env
7762632Sstever@eecs.umich.edu        def __getattr__(self, mname):
7772632Sstever@eecs.umich.edu            return NullCheck
7782632Sstever@eecs.umich.edu
7792632Sstever@eecs.umich.edu    conf = NullConf(main)
7803716Sstever@eecs.umich.edu
7813716Sstever@eecs.umich.edu# Find Python include and library directories for embedding the
7825342Sstever@gmail.com# interpreter.  For consistency, we will use the same Python
7832632Sstever@eecs.umich.edu# installation used to run scons (and thus this script).  If you want
7842632Sstever@eecs.umich.edu# to link in an alternate version, see above for instructions on how
7852632Sstever@eecs.umich.edu# to invoke scons with a different copy of the Python interpreter.
7862632Sstever@eecs.umich.edufrom distutils import sysconfig
7872632Sstever@eecs.umich.edu
7882632Sstever@eecs.umich.edupy_getvar = sysconfig.get_config_var
7892632Sstever@eecs.umich.edu
7901888SN/Apy_debug = getattr(sys, 'pydebug', False)
7911888SN/Apy_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
7921869SN/A
7931869SN/Apy_general_include = sysconfig.get_python_inc()
7941858SN/Apy_platform_include = sysconfig.get_python_inc(plat_specific=True)
7955341Sstever@gmail.compy_includes = [ py_general_include ]
7962598SN/Aif py_platform_include != py_general_include:
7972598SN/A    py_includes.append(py_platform_include)
7982598SN/A
7992598SN/Apy_lib_path = [ py_getvar('LIBDIR') ]
8001858SN/A# add the prefix/lib/pythonX.Y/config dir, but only if there is no
8011858SN/A# shared library in prefix/lib/.
8021858SN/Aif not py_getvar('Py_ENABLE_SHARED'):
8031858SN/A    py_lib_path.append(py_getvar('LIBPL'))
8041858SN/A
8051858SN/Apy_libs = []
8061858SN/Afor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
8071858SN/A    if not lib.startswith('-l'):
8081858SN/A        # Python requires some special flags to link (e.g. -framework
8091871SN/A        # common on OS X systems), assume appending preserves order
8101858SN/A        main.Append(LINKFLAGS=[lib])
8111858SN/A    else:
8121858SN/A        lib = lib[2:]
8131858SN/A        if lib not in py_libs:
8141858SN/A            py_libs.append(lib)
8151858SN/Apy_libs.append(py_version)
8161858SN/A
8171858SN/Amain.Append(CPPPATH=py_includes)
8181858SN/Amain.Append(LIBPATH=py_lib_path)
8191858SN/A
8201858SN/A# Cache build files in the supplied directory.
8211859SN/Aif main['M5_BUILD_CACHE']:
8221859SN/A    print 'Using build cache located at', main['M5_BUILD_CACHE']
8231869SN/A    CacheDir(main['M5_BUILD_CACHE'])
8241888SN/A
8252632Sstever@eecs.umich.edu
8261869SN/A# verify that this stuff works
8271965SN/Aif not conf.CheckHeader('Python.h', '<>'):
8281965SN/A    print "Error: can't find Python.h header in", py_includes
8291965SN/A    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8302761Sstever@eecs.umich.edu    Exit(1)
8311869SN/A
8321869SN/Afor lib in py_libs:
8332632Sstever@eecs.umich.edu    if not conf.CheckLib(lib):
8342667Sstever@eecs.umich.edu        print "Error: can't find library %s required by python" % lib
8351869SN/A        Exit(1)
8361869SN/A
8372929Sktlim@umich.edu# On Solaris you need to use libsocket for socket ops
8382929Sktlim@umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8393716Sstever@eecs.umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8402929Sktlim@umich.edu       print "Can't find library with socket calls (e.g. accept())"
841955SN/A       Exit(1)
8422598SN/A
8432598SN/A# Check for zlib.  If the check passes, libz will be automatically
8443546Sgblack@eecs.umich.edu# added to the LIBS environment variable.
845955SN/Aif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
846955SN/A    print 'Error: did not find needed zlib compression library '\
847955SN/A          'and/or zlib.h header file.'
8481530SN/A    print '       Please install zlib and try again.'
849955SN/A    Exit(1)
850955SN/A
851955SN/A# If we have the protobuf compiler, also make sure we have the
852# development libraries. If the check passes, libprotobuf will be
853# automatically added to the LIBS environment variable. After
854# this, we can use the HAVE_PROTOBUF flag to determine if we have
855# got both protoc and libprotobuf available.
856main['HAVE_PROTOBUF'] = main['PROTOC'] and \
857    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
858                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
859
860# If we have the compiler but not the library, print another warning.
861if main['PROTOC'] and not main['HAVE_PROTOBUF']:
862    print termcap.Yellow + termcap.Bold + \
863        'Warning: did not find protocol buffer library and/or headers.\n' + \
864    '       Please install libprotobuf-dev for tracing support.' + \
865    termcap.Normal
866
867# Check for librt.
868have_posix_clock = \
869    conf.CheckLibWithHeader(None, 'time.h', 'C',
870                            'clock_nanosleep(0,0,NULL,NULL);') or \
871    conf.CheckLibWithHeader('rt', 'time.h', 'C',
872                            'clock_nanosleep(0,0,NULL,NULL);')
873
874if conf.CheckLib('tcmalloc_minimal'):
875    have_tcmalloc = True
876else:
877    have_tcmalloc = False
878    print termcap.Yellow + termcap.Bold + \
879          "You can get a 12% performance improvement by installing tcmalloc "\
880          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
881          termcap.Normal
882
883if not have_posix_clock:
884    print "Can't find library for POSIX clocks."
885
886# Check for <fenv.h> (C99 FP environment control)
887have_fenv = conf.CheckHeader('fenv.h', '<>')
888if not have_fenv:
889    print "Warning: Header file <fenv.h> not found."
890    print "         This host has no IEEE FP rounding mode control."
891
892######################################################################
893#
894# Finish the configuration
895#
896main = conf.Finish()
897
898######################################################################
899#
900# Collect all non-global variables
901#
902
903# Define the universe of supported ISAs
904all_isa_list = [ ]
905Export('all_isa_list')
906
907class CpuModel(object):
908    '''The CpuModel class encapsulates everything the ISA parser needs to
909    know about a particular CPU model.'''
910
911    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
912    dict = {}
913    list = []
914    defaults = []
915
916    # Constructor.  Automatically adds models to CpuModel.dict.
917    def __init__(self, name, filename, includes, strings, default=False):
918        self.name = name           # name of model
919        self.filename = filename   # filename for output exec code
920        self.includes = includes   # include files needed in exec file
921        # The 'strings' dict holds all the per-CPU symbols we can
922        # substitute into templates etc.
923        self.strings = strings
924
925        # This cpu is enabled by default
926        self.default = default
927
928        # Add self to dict
929        if name in CpuModel.dict:
930            raise AttributeError, "CpuModel '%s' already registered" % name
931        CpuModel.dict[name] = self
932        CpuModel.list.append(name)
933
934Export('CpuModel')
935
936# Sticky variables get saved in the variables file so they persist from
937# one invocation to the next (unless overridden, in which case the new
938# value becomes sticky).
939sticky_vars = Variables(args=ARGUMENTS)
940Export('sticky_vars')
941
942# Sticky variables that should be exported
943export_vars = []
944Export('export_vars')
945
946# For Ruby
947all_protocols = []
948Export('all_protocols')
949protocol_dirs = []
950Export('protocol_dirs')
951slicc_includes = []
952Export('slicc_includes')
953
954# Walk the tree and execute all SConsopts scripts that wil add to the
955# above variables
956if not GetOption('verbose'):
957    print "Reading SConsopts"
958for bdir in [ base_dir ] + extras_dir_list:
959    if not isdir(bdir):
960        print "Error: directory '%s' does not exist" % bdir
961        Exit(1)
962    for root, dirs, files in os.walk(bdir):
963        if 'SConsopts' in files:
964            if GetOption('verbose'):
965                print "Reading", joinpath(root, 'SConsopts')
966            SConscript(joinpath(root, 'SConsopts'))
967
968all_isa_list.sort()
969
970sticky_vars.AddVariables(
971    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
972    ListVariable('CPU_MODELS', 'CPU models',
973                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
974                 sorted(CpuModel.list)),
975    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
976                 False),
977    BoolVariable('SS_COMPATIBLE_FP',
978                 'Make floating-point results compatible with SimpleScalar',
979                 False),
980    BoolVariable('USE_SSE2',
981                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
982                 False),
983    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
984    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
985    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
986    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
987                  all_protocols),
988    )
989
990# These variables get exported to #defines in config/*.hh (see src/SConscript).
991export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
992                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
993
994###################################################
995#
996# Define a SCons builder for configuration flag headers.
997#
998###################################################
999
1000# This function generates a config header file that #defines the
1001# variable symbol to the current variable setting (0 or 1).  The source
1002# operands are the name of the variable and a Value node containing the
1003# value of the variable.
1004def build_config_file(target, source, env):
1005    (variable, value) = [s.get_contents() for s in source]
1006    f = file(str(target[0]), 'w')
1007    print >> f, '#define', variable, value
1008    f.close()
1009    return None
1010
1011# Combine the two functions into a scons Action object.
1012config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1013
1014# The emitter munges the source & target node lists to reflect what
1015# we're really doing.
1016def config_emitter(target, source, env):
1017    # extract variable name from Builder arg
1018    variable = str(target[0])
1019    # True target is config header file
1020    target = joinpath('config', variable.lower() + '.hh')
1021    val = env[variable]
1022    if isinstance(val, bool):
1023        # Force value to 0/1
1024        val = int(val)
1025    elif isinstance(val, str):
1026        val = '"' + val + '"'
1027
1028    # Sources are variable name & value (packaged in SCons Value nodes)
1029    return ([target], [Value(variable), Value(val)])
1030
1031config_builder = Builder(emitter = config_emitter, action = config_action)
1032
1033main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1034
1035# libelf build is shared across all configs in the build root.
1036main.SConscript('ext/libelf/SConscript',
1037                variant_dir = joinpath(build_root, 'libelf'))
1038
1039# gzstream build is shared across all configs in the build root.
1040main.SConscript('ext/gzstream/SConscript',
1041                variant_dir = joinpath(build_root, 'gzstream'))
1042
1043###################################################
1044#
1045# This function is used to set up a directory with switching headers
1046#
1047###################################################
1048
1049main['ALL_ISA_LIST'] = all_isa_list
1050def make_switching_dir(dname, switch_headers, env):
1051    # Generate the header.  target[0] is the full path of the output
1052    # header to generate.  'source' is a dummy variable, since we get the
1053    # list of ISAs from env['ALL_ISA_LIST'].
1054    def gen_switch_hdr(target, source, env):
1055        fname = str(target[0])
1056        f = open(fname, 'w')
1057        isa = env['TARGET_ISA'].lower()
1058        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1059        f.close()
1060
1061    # Build SCons Action object. 'varlist' specifies env vars that this
1062    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1063    # should get re-executed.
1064    switch_hdr_action = MakeAction(gen_switch_hdr,
1065                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1066
1067    # Instantiate actions for each header
1068    for hdr in switch_headers:
1069        env.Command(hdr, [], switch_hdr_action)
1070Export('make_switching_dir')
1071
1072###################################################
1073#
1074# Define build environments for selected configurations.
1075#
1076###################################################
1077
1078for variant_path in variant_paths:
1079    print "Building in", variant_path
1080
1081    # Make a copy of the build-root environment to use for this config.
1082    env = main.Clone()
1083    env['BUILDDIR'] = variant_path
1084
1085    # variant_dir is the tail component of build path, and is used to
1086    # determine the build parameters (e.g., 'ALPHA_SE')
1087    (build_root, variant_dir) = splitpath(variant_path)
1088
1089    # Set env variables according to the build directory config.
1090    sticky_vars.files = []
1091    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1092    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1093    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1094    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1095    if isfile(current_vars_file):
1096        sticky_vars.files.append(current_vars_file)
1097        print "Using saved variables file %s" % current_vars_file
1098    else:
1099        # Build dir-specific variables file doesn't exist.
1100
1101        # Make sure the directory is there so we can create it later
1102        opt_dir = dirname(current_vars_file)
1103        if not isdir(opt_dir):
1104            mkdir(opt_dir)
1105
1106        # Get default build variables from source tree.  Variables are
1107        # normally determined by name of $VARIANT_DIR, but can be
1108        # overridden by '--default=' arg on command line.
1109        default = GetOption('default')
1110        opts_dir = joinpath(main.root.abspath, 'build_opts')
1111        if default:
1112            default_vars_files = [joinpath(build_root, 'variables', default),
1113                                  joinpath(opts_dir, default)]
1114        else:
1115            default_vars_files = [joinpath(opts_dir, variant_dir)]
1116        existing_files = filter(isfile, default_vars_files)
1117        if existing_files:
1118            default_vars_file = existing_files[0]
1119            sticky_vars.files.append(default_vars_file)
1120            print "Variables file %s not found,\n  using defaults in %s" \
1121                  % (current_vars_file, default_vars_file)
1122        else:
1123            print "Error: cannot find variables file %s or " \
1124                  "default file(s) %s" \
1125                  % (current_vars_file, ' or '.join(default_vars_files))
1126            Exit(1)
1127
1128    # Apply current variable settings to env
1129    sticky_vars.Update(env)
1130
1131    help_texts["local_vars"] += \
1132        "Build variables for %s:\n" % variant_dir \
1133                 + sticky_vars.GenerateHelpText(env)
1134
1135    # Process variable settings.
1136
1137    if not have_fenv and env['USE_FENV']:
1138        print "Warning: <fenv.h> not available; " \
1139              "forcing USE_FENV to False in", variant_dir + "."
1140        env['USE_FENV'] = False
1141
1142    if not env['USE_FENV']:
1143        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1144        print "         FP results may deviate slightly from other platforms."
1145
1146    if env['EFENCE']:
1147        env.Append(LIBS=['efence'])
1148
1149    # Save sticky variable settings back to current variables file
1150    sticky_vars.Save(current_vars_file, env)
1151
1152    if env['USE_SSE2']:
1153        env.Append(CCFLAGS=['-msse2'])
1154
1155    if have_tcmalloc:
1156        env.Append(LIBS=['tcmalloc_minimal'])
1157
1158    # The src/SConscript file sets up the build rules in 'env' according
1159    # to the configured variables.  It returns a list of environments,
1160    # one for each variant build (debug, opt, etc.)
1161    envList = SConscript('src/SConscript', variant_dir = variant_path,
1162                         exports = 'env')
1163
1164    # Set up the regression tests for each build.
1165    for e in envList:
1166        SConscript('tests/SConscript',
1167                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1168                   exports = { 'env' : e }, duplicate = False)
1169
1170# base help text
1171Help('''
1172Usage: scons [scons options] [build variables] [target(s)]
1173
1174Extra scons options:
1175%(options)s
1176
1177Global build variables:
1178%(global_vars)s
1179
1180%(local_vars)s
1181''' % help_texts)
1182