SConstruct revision 8946
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.edu
1248120Sgblack@eecs.umich.eduhelp_texts = {
1258120Sgblack@eecs.umich.edu    "options" : "",
1268120Sgblack@eecs.umich.edu    "global_vars" : "",
1278120Sgblack@eecs.umich.edu    "local_vars" : ""
1288120Sgblack@eecs.umich.edu}
1298120Sgblack@eecs.umich.edu
1308120Sgblack@eecs.umich.eduExport("help_texts")
1318120Sgblack@eecs.umich.edu
1328120Sgblack@eecs.umich.edu
1338120Sgblack@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1348120Sgblack@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1358120Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1368120Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1378120Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1388120Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1398120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1408120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1418120Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1428120Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1438120Sgblack@eecs.umich.edu# we can just use AddOption directly.
1448120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1458120Sgblack@eecs.umich.edu    col_width = 30
1468120Sgblack@eecs.umich.edu
1478120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1488120Sgblack@eecs.umich.edu    if "help" in kwargs:
1498120Sgblack@eecs.umich.edu        length = len(help)
1508120Sgblack@eecs.umich.edu        if length >= col_width:
1518120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1528120Sgblack@eecs.umich.edu        else:
1538120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1548120Sgblack@eecs.umich.edu        help += kwargs["help"]
1558120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1568120Sgblack@eecs.umich.edu
1578120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1588120Sgblack@eecs.umich.edu
1598120Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1607816Ssteve.reinhardt@amd.com               help="Add color to abbreviated scons output")
1617816Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1627816Ssteve.reinhardt@amd.com               help="Don't add color to abbreviated scons output")
1637816Ssteve.reinhardt@amd.comAddLocalOption('--default', dest='default', type='string', action='store',
1647816Ssteve.reinhardt@amd.com               help='Override which build_opts file to use for defaults')
1657816Ssteve.reinhardt@amd.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1667816Ssteve.reinhardt@amd.com               help='Disable style checking hooks')
1677816Ssteve.reinhardt@amd.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1687816Ssteve.reinhardt@amd.com               help='Update test reference outputs')
1695871Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1705871Snate@binkert.org               help='Print full tool command lines')
1716121Snate@binkert.org
1725871Snate@binkert.orguse_colors = GetOption('use_colors')
1735871Snate@binkert.orgif use_colors:
1746003Snate@binkert.org    from m5.util.terminal import termcap
1756655Snate@binkert.orgelif use_colors is None:
176955SN/A    # option unspecified; default behavior is to use colors iff isatty
1775871Snate@binkert.org    from m5.util.terminal import tty_termcap as termcap
1785871Snate@binkert.orgelse:
1795871Snate@binkert.org    from m5.util.terminal import no_termcap as termcap
1805871Snate@binkert.org
181955SN/A########################################################################
1826121Snate@binkert.org#
1836121Snate@binkert.org# Set up the main build environment.
1846121Snate@binkert.org#
1851533SN/A########################################################################
1866655Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
1876655Snate@binkert.org                 'PYTHONPATH', 'RANLIB' ])
1886655Snate@binkert.org
1896655Snate@binkert.orguse_env = {}
1905871Snate@binkert.orgfor key,val in os.environ.iteritems():
1915871Snate@binkert.org    if key in use_vars or key.startswith("M5"):
1925863Snate@binkert.org        use_env[key] = val
1935871Snate@binkert.org
1945871Snate@binkert.orgmain = Environment(ENV=use_env)
1955871Snate@binkert.orgmain.Decider('MD5-timestamp')
1965871Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
1975871Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
1985863Snate@binkert.org
1996121Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2005863Snate@binkert.org# as well
2015871Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2028336Ssteve.reinhardt@amd.com
2038336Ssteve.reinhardt@amd.com########################################################################
2048336Ssteve.reinhardt@amd.com#
2058336Ssteve.reinhardt@amd.com# Mercurial Stuff.
2064678Snate@binkert.org#
2078336Ssteve.reinhardt@amd.com# If the gem5 directory is a mercurial repository, we should do some
2088336Ssteve.reinhardt@amd.com# extra things.
2098336Ssteve.reinhardt@amd.com#
2104678Snate@binkert.org########################################################################
2114678Snate@binkert.org
2124678Snate@binkert.orghgdir = main.root.Dir(".hg")
2134678Snate@binkert.org
2147827Snate@binkert.orgmercurial_style_message = """
2157827Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2168336Ssteve.reinhardt@amd.comagainst the gem5 style rules on hg commit and qrefresh commands.  This
2174678Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
2188336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2198336Ssteve.reinhardt@amd.com
2208336Ssteve.reinhardt@amd.commercurial_style_hook = """
2218336Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2228336Ssteve.reinhardt@amd.com# to provide the gem5 style-checking hooks
2238336Ssteve.reinhardt@amd.com[extensions]
2245871Snate@binkert.orgstyle = %s/util/style.py
2255871Snate@binkert.org
2268336Ssteve.reinhardt@amd.com[hooks]
2278336Ssteve.reinhardt@amd.compretxncommit.style = python:style.check_style
2288336Ssteve.reinhardt@amd.compre-qrefresh.style = python:style.check_style
2298336Ssteve.reinhardt@amd.com# End of SConstruct additions
2308336Ssteve.reinhardt@amd.com
2315871Snate@binkert.org""" % (main.root.abspath)
2328336Ssteve.reinhardt@amd.com
2338336Ssteve.reinhardt@amd.commercurial_lib_not_found = """
2348336Ssteve.reinhardt@amd.comMercurial libraries cannot be found, ignoring style hook.  If
2358336Ssteve.reinhardt@amd.comyou are a gem5 developer, please fix this and run the style
2368336Ssteve.reinhardt@amd.comhook. It is important.
2374678Snate@binkert.org"""
2385871Snate@binkert.org
2394678Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
2408336Ssteve.reinhardt@amd.com# Skip this if --ignore-style was specified, there's no .hg dir to
2418336Ssteve.reinhardt@amd.com# install a hook in, or there's no interactive terminal to prompt.
2428336Ssteve.reinhardt@amd.comif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2438336Ssteve.reinhardt@amd.com    style_hook = True
2448336Ssteve.reinhardt@amd.com    try:
2458336Ssteve.reinhardt@amd.com        from mercurial import ui
2468336Ssteve.reinhardt@amd.com        ui = ui.ui()
2478336Ssteve.reinhardt@amd.com        ui.readconfig(hgdir.File('hgrc').abspath)
2488336Ssteve.reinhardt@amd.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2498336Ssteve.reinhardt@amd.com                     ui.config('hooks', 'pre-qrefresh.style', None)
2508336Ssteve.reinhardt@amd.com    except ImportError:
2518336Ssteve.reinhardt@amd.com        print mercurial_lib_not_found
2528336Ssteve.reinhardt@amd.com
2538336Ssteve.reinhardt@amd.com    if not style_hook:
2548336Ssteve.reinhardt@amd.com        print mercurial_style_message,
2558336Ssteve.reinhardt@amd.com        # continue unless user does ctrl-c/ctrl-d etc.
2568336Ssteve.reinhardt@amd.com        try:
2575871Snate@binkert.org            raw_input()
2586121Snate@binkert.org        except:
259955SN/A            print "Input exception, exiting scons.\n"
260955SN/A            sys.exit(1)
2612632Sstever@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2622632Sstever@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
263955SN/A        try:
264955SN/A            hgrc = open(hgrc_path, 'a')
265955SN/A            hgrc.write(mercurial_style_hook)
266955SN/A            hgrc.close()
2675863Snate@binkert.org        except:
268955SN/A            print "Error updating", hgrc_path
2692632Sstever@eecs.umich.edu            sys.exit(1)
2702632Sstever@eecs.umich.edu
2712632Sstever@eecs.umich.edu
2722632Sstever@eecs.umich.edu###################################################
2732632Sstever@eecs.umich.edu#
2742632Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
2752632Sstever@eecs.umich.edu# the target(s).
2768268Ssteve.reinhardt@amd.com#
2778268Ssteve.reinhardt@amd.com###################################################
2788268Ssteve.reinhardt@amd.com
2798268Ssteve.reinhardt@amd.com# Find default configuration & binary.
2808268Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2818268Ssteve.reinhardt@amd.com
2828268Ssteve.reinhardt@amd.com# helper function: find last occurrence of element in list
2832632Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2842632Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2852632Sstever@eecs.umich.edu        if l[i] == elt:
2862632Sstever@eecs.umich.edu            return i
2878268Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
2882632Sstever@eecs.umich.edu
2898268Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
2908268Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
2918268Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
2928268Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2933718Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
2942634Sstever@eecs.umich.edu            for p in path_list]
2952634Sstever@eecs.umich.edu
2965863Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2972638Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2988268Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2992632Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3002632Sstever@eecs.umich.edu# follow 'build' in the build path.
3012632Sstever@eecs.umich.edu
3022632Sstever@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
3032632Sstever@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
3041858SN/A# doesn't work (obviously!).
3053716Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3062638Sstever@eecs.umich.edu
3072638Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
3082638Sstever@eecs.umich.edu# collected targets reference.
3092638Sstever@eecs.umich.eduvariant_paths = []
3102638Sstever@eecs.umich.edubuild_root = None
3112638Sstever@eecs.umich.edufor t in BUILD_TARGETS:
3122638Sstever@eecs.umich.edu    path_dirs = t.split('/')
3135863Snate@binkert.org    try:
3145863Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
3155863Snate@binkert.org    except:
316955SN/A        print "Error: no non-leaf 'build' dir found on target path", t
3175341Sstever@gmail.com        Exit(1)
3185341Sstever@gmail.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3195863Snate@binkert.org    if not build_root:
3207756SAli.Saidi@ARM.com        build_root = this_build_root
3215341Sstever@gmail.com    else:
3226121Snate@binkert.org        if this_build_root != build_root:
3234494Ssaidi@eecs.umich.edu            print "Error: build targets not under same build root\n"\
3246121Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3251105SN/A            Exit(1)
3262667Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3272667Sstever@eecs.umich.edu    if variant_path not in variant_paths:
3282667Sstever@eecs.umich.edu        variant_paths.append(variant_path)
3292667Sstever@eecs.umich.edu
3306121Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
3312667Sstever@eecs.umich.eduif not isdir(build_root):
3325341Sstever@gmail.com    mkdir(build_root)
3335863Snate@binkert.orgmain['BUILDROOT'] = build_root
3345341Sstever@gmail.com
3355341Sstever@gmail.comExport('main')
3365341Sstever@gmail.com
3378120Sgblack@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
3385341Sstever@gmail.com
3398120Sgblack@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
3405341Sstever@gmail.com# when you use emacs to edit a file in the target dir, as emacs moves
3418120Sgblack@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3426121Snate@binkert.org# (soft) links work better.
3436121Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
3445397Ssaidi@eecs.umich.edu
3455397Ssaidi@eecs.umich.edu#
3467727SAli.Saidi@ARM.com# Set up global sticky variables... these are common to an entire build
3478268Ssteve.reinhardt@amd.com# tree (not specific to a particular build like ALPHA_SE)
3486168Snate@binkert.org#
3495341Sstever@gmail.com
3508120Sgblack@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3518120Sgblack@eecs.umich.edu
3528120Sgblack@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3536814Sgblack@eecs.umich.edu
3545863Snate@binkert.orgglobal_vars.AddVariables(
3558120Sgblack@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3565341Sstever@gmail.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3575863Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
3588268Ssteve.reinhardt@amd.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3596121Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3606121Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
3618268Ssteve.reinhardt@amd.com    )
3625742Snate@binkert.org
3635742Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
3645341Sstever@gmail.comglobal_vars.Update(main)
3655742Snate@binkert.orghelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3665742Snate@binkert.org
3675341Sstever@gmail.com# Save sticky variable settings back to current variables file
3686017Snate@binkert.orgglobal_vars.Save(global_vars_file, main)
3696121Snate@binkert.org
3706017Snate@binkert.org# Parse EXTRAS variable to build list of all directories where we're
3717816Ssteve.reinhardt@amd.com# look for sources etc.  This list is exported as extras_dir_list.
3727756SAli.Saidi@ARM.combase_dir = main.srcdir.abspath
3737756SAli.Saidi@ARM.comif main['EXTRAS']:
3747756SAli.Saidi@ARM.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3757756SAli.Saidi@ARM.comelse:
3767756SAli.Saidi@ARM.com    extras_dir_list = []
3777756SAli.Saidi@ARM.com
3787756SAli.Saidi@ARM.comExport('base_dir')
3797756SAli.Saidi@ARM.comExport('extras_dir_list')
3807816Ssteve.reinhardt@amd.com
3817816Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
3827816Ssteve.reinhardt@amd.commain.Append(CPPPATH=[Dir('ext')])
3837816Ssteve.reinhardt@amd.com
3847816Ssteve.reinhardt@amd.comdef strip_build_path(path, env):
3857816Ssteve.reinhardt@amd.com    path = str(path)
3867816Ssteve.reinhardt@amd.com    variant_base = env['BUILDROOT'] + os.path.sep
3877816Ssteve.reinhardt@amd.com    if path.startswith(variant_base):
3887816Ssteve.reinhardt@amd.com        path = path[len(variant_base):]
3897816Ssteve.reinhardt@amd.com    elif path.startswith('build/'):
3907756SAli.Saidi@ARM.com        path = path[6:]
3917816Ssteve.reinhardt@amd.com    return path
3927816Ssteve.reinhardt@amd.com
3937816Ssteve.reinhardt@amd.com# Generate a string of the form:
3947816Ssteve.reinhardt@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
3957816Ssteve.reinhardt@amd.com# to print while building.
3967816Ssteve.reinhardt@amd.comclass Transform(object):
3977816Ssteve.reinhardt@amd.com    # all specific color settings should be here and nowhere else
3987816Ssteve.reinhardt@amd.com    tool_color = termcap.Normal
3997816Ssteve.reinhardt@amd.com    pfx_color = termcap.Yellow
4007816Ssteve.reinhardt@amd.com    srcs_color = termcap.Yellow + termcap.Bold
4017816Ssteve.reinhardt@amd.com    arrow_color = termcap.Blue + termcap.Bold
4027816Ssteve.reinhardt@amd.com    tgts_color = termcap.Yellow + termcap.Bold
4037816Ssteve.reinhardt@amd.com
4047816Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
4057816Ssteve.reinhardt@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
4067816Ssteve.reinhardt@amd.com                      + self.pfx_color + "%s" \
4077816Ssteve.reinhardt@amd.com                      + self.srcs_color + "%s" \
4087816Ssteve.reinhardt@amd.com                      + self.arrow_color + " -> " \
4097816Ssteve.reinhardt@amd.com                      + self.tgts_color + "%s" \
4107816Ssteve.reinhardt@amd.com                      + termcap.Normal
4117816Ssteve.reinhardt@amd.com        self.max_sources = max_sources
4127816Ssteve.reinhardt@amd.com
4137816Ssteve.reinhardt@amd.com    def __call__(self, target, source, env, for_signature=None):
4147816Ssteve.reinhardt@amd.com        # truncate source list according to max_sources param
4157816Ssteve.reinhardt@amd.com        source = source[0:self.max_sources]
4167816Ssteve.reinhardt@amd.com        def strip(f):
4177816Ssteve.reinhardt@amd.com            return strip_build_path(str(f), env)
4187816Ssteve.reinhardt@amd.com        if len(source) > 0:
4197816Ssteve.reinhardt@amd.com            srcs = map(strip, source)
4207816Ssteve.reinhardt@amd.com        else:
4217816Ssteve.reinhardt@amd.com            srcs = ['']
4227816Ssteve.reinhardt@amd.com        tgts = map(strip, target)
4237816Ssteve.reinhardt@amd.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4247816Ssteve.reinhardt@amd.com        # operation that has nothing to do with paths.
4257816Ssteve.reinhardt@amd.com        com_pfx = os.path.commonprefix(srcs + tgts)
4267816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4277816Ssteve.reinhardt@amd.com        if com_pfx:
4287816Ssteve.reinhardt@amd.com            # do some cleanup and sanity checking on common prefix
4297816Ssteve.reinhardt@amd.com            if com_pfx[-1] == ".":
4307816Ssteve.reinhardt@amd.com                # prefix matches all but file extension: ok
4317816Ssteve.reinhardt@amd.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4327816Ssteve.reinhardt@amd.com                com_pfx = com_pfx[0:-1]
4337816Ssteve.reinhardt@amd.com            elif com_pfx[-1] == "/":
4347816Ssteve.reinhardt@amd.com                # common prefix is directory path: OK
4357816Ssteve.reinhardt@amd.com                pass
4367816Ssteve.reinhardt@amd.com            else:
4377816Ssteve.reinhardt@amd.com                src0_len = len(srcs[0])
4387816Ssteve.reinhardt@amd.com                tgt0_len = len(tgts[0])
4397816Ssteve.reinhardt@amd.com                if src0_len == com_pfx_len:
4407816Ssteve.reinhardt@amd.com                    # source is a substring of target, OK
4417816Ssteve.reinhardt@amd.com                    pass
4427816Ssteve.reinhardt@amd.com                elif tgt0_len == com_pfx_len:
4437816Ssteve.reinhardt@amd.com                    # target is a substring of source, need to back up to
4447816Ssteve.reinhardt@amd.com                    # avoid empty string on RHS of arrow
4457816Ssteve.reinhardt@amd.com                    sep_idx = com_pfx.rfind(".")
4467816Ssteve.reinhardt@amd.com                    if sep_idx != -1:
4477816Ssteve.reinhardt@amd.com                        com_pfx = com_pfx[0:sep_idx]
4487816Ssteve.reinhardt@amd.com                    else:
4497816Ssteve.reinhardt@amd.com                        com_pfx = ''
4507816Ssteve.reinhardt@amd.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4517816Ssteve.reinhardt@amd.com                    # still splitting at file extension: ok
4527756SAli.Saidi@ARM.com                    pass
4538120Sgblack@eecs.umich.edu                else:
4547756SAli.Saidi@ARM.com                    # probably a fluke; ignore it
4557756SAli.Saidi@ARM.com                    com_pfx = ''
4567756SAli.Saidi@ARM.com        # recalculate length in case com_pfx was modified
4577756SAli.Saidi@ARM.com        com_pfx_len = len(com_pfx)
4587816Ssteve.reinhardt@amd.com        def fmt(files):
4597816Ssteve.reinhardt@amd.com            f = map(lambda s: s[com_pfx_len:], files)
4607816Ssteve.reinhardt@amd.com            return ', '.join(f)
4617816Ssteve.reinhardt@amd.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4627816Ssteve.reinhardt@amd.com
4637816Ssteve.reinhardt@amd.comExport('Transform')
4647816Ssteve.reinhardt@amd.com
4657816Ssteve.reinhardt@amd.com
4667816Ssteve.reinhardt@amd.comif GetOption('verbose'):
4677816Ssteve.reinhardt@amd.com    def MakeAction(action, string, *args, **kwargs):
4687756SAli.Saidi@ARM.com        return Action(action, *args, **kwargs)
4697756SAli.Saidi@ARM.comelse:
4706654Snate@binkert.org    MakeAction = Action
4716654Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
4725871Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
4736121Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
4746121Snate@binkert.org    main['SWIGCOMSTR']      = Transform("SWIG")
4756121Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
4766121Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
4773940Ssaidi@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4783918Ssaidi@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
4793918Ssaidi@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
4801858SN/A    main['SHCXXCOMSTR']     = Transform("SHCXX")
4816121Snate@binkert.orgExport('MakeAction')
4827739Sgblack@eecs.umich.edu
4837739Sgblack@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
4846143Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
4857739Sgblack@eecs.umich.edu
4867618SAli.Saidi@arm.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
4877618SAli.Saidi@arm.commain['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
4887618SAli.Saidi@arm.commain['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
4897618SAli.Saidi@arm.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
4907618SAli.Saidi@arm.comif main['GCC'] + main['SUNCC'] + main['ICC'] + main['CLANG'] > 1:
4917618SAli.Saidi@arm.com    print 'Error: How can we have two at the same time?'
4927618SAli.Saidi@arm.com    Exit(1)
4937739Sgblack@eecs.umich.edu
4946121Snate@binkert.org# Set up default C++ compiler flags
4953940Ssaidi@eecs.umich.eduif main['GCC']:
4966121Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
4977739Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
4987739Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
4997739Sgblack@eecs.umich.edu    # Read the GCC version to check for versions with bugs
5007739Sgblack@eecs.umich.edu    # Note CCVERSION doesn't work here because it is run with the CC
5017739Sgblack@eecs.umich.edu    # before we override it from the command line
5027739Sgblack@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5033918Ssaidi@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
5043918Ssaidi@eecs.umich.edu    if not compareVersions(gcc_version, '4.4.1') or \
5053940Ssaidi@eecs.umich.edu       not compareVersions(gcc_version, '4.4.2'):
5063918Ssaidi@eecs.umich.edu        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5073918Ssaidi@eecs.umich.edu        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5086157Snate@binkert.org    if compareVersions(gcc_version, '4.6') >= 0:
5096157Snate@binkert.org        main.Append(CXXFLAGS=['-std=c++0x'])
5106157Snate@binkert.orgelif main['ICC']:
5116157Snate@binkert.org    pass #Fix me... add warning flags once we clean up icc warnings
5125397Ssaidi@eecs.umich.eduelif main['SUNCC']:
5135397Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Qoption ccfe'])
5146121Snate@binkert.org    main.Append(CCFLAGS=['-features=gcc'])
5156121Snate@binkert.org    main.Append(CCFLAGS=['-features=extensions'])
5166121Snate@binkert.org    main.Append(CCFLAGS=['-library=stlport4'])
5176121Snate@binkert.org    main.Append(CCFLAGS=['-xar'])
5186121Snate@binkert.org    #main.Append(CCFLAGS=['-instances=semiexplicit'])
5196121Snate@binkert.orgelif main['CLANG']:
5205397Ssaidi@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
5211851SN/A    clang_version_match = clang_version_re.match(CXX_version)
5221851SN/A    if (clang_version_match):
5237739Sgblack@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
524955SN/A        if compareVersions(clang_version, "2.9") < 0:
5253053Sstever@eecs.umich.edu            print 'Error: clang version 2.9 or newer required.'
5266121Snate@binkert.org            print '       Installed version:', clang_version
5273053Sstever@eecs.umich.edu            Exit(1)
5283053Sstever@eecs.umich.edu    else:
5293053Sstever@eecs.umich.edu        print 'Error: Unable to determine clang version.'
5303053Sstever@eecs.umich.edu        Exit(1)
5313053Sstever@eecs.umich.edu
5326654Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
5333053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5344742Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5354742Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-tautological-compare'])
5363053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-self-assign'])
5373053Sstever@eecs.umich.edu    # Ruby makes frequent use of extraneous parantheses in the printing
5383053Sstever@eecs.umich.edu    # of if-statements
5393053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses'])
5406654Snate@binkert.org
5413053Sstever@eecs.umich.edu    if compareVersions(clang_version, "3") >= 0:
5423053Sstever@eecs.umich.edu        main.Append(CXXFLAGS=['-std=c++0x'])
5433053Sstever@eecs.umich.eduelse:
5443053Sstever@eecs.umich.edu    print 'Error: Don\'t know what compiler options to use for your compiler.'
5452667Sstever@eecs.umich.edu    print '       Please fix SConstruct and src/SConscript and try again.'
5464554Sbinkertn@umich.edu    Exit(1)
5476121Snate@binkert.org
5482667Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
5494554Sbinkertn@umich.edumain['YACCFLAGS'] = '-d'
5504554Sbinkertn@umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5514554Sbinkertn@umich.edu
5526121Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
5534554Sbinkertn@umich.edu# extra 'qdo' every time we run scons.
5544554Sbinkertn@umich.eduif main['BATCH']:
5554554Sbinkertn@umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5564781Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5574554Sbinkertn@umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5584554Sbinkertn@umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5592667Sstever@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5604554Sbinkertn@umich.edu
5614554Sbinkertn@umich.eduif sys.platform == 'cygwin':
5624554Sbinkertn@umich.edu    # cygwin has some header file issues...
5634554Sbinkertn@umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
5642667Sstever@eecs.umich.edu
5654554Sbinkertn@umich.edu# Check for SWIG
5662667Sstever@eecs.umich.eduif not main.has_key('SWIG'):
5674554Sbinkertn@umich.edu    print 'Error: SWIG utility not found.'
5686121Snate@binkert.org    print '       Please install (see http://www.swig.org) and retry.'
5692667Sstever@eecs.umich.edu    Exit(1)
5705522Snate@binkert.org
5715522Snate@binkert.org# Check for appropriate SWIG version
5725522Snate@binkert.orgswig_version = readCommand(('swig', '-version'), exception='').split()
5735522Snate@binkert.org# First 3 words should be "SWIG Version x.y.z"
5745522Snate@binkert.orgif len(swig_version) < 3 or \
5755522Snate@binkert.org        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
5765522Snate@binkert.org    print 'Error determining SWIG version.'
5775522Snate@binkert.org    Exit(1)
5785522Snate@binkert.org
5795522Snate@binkert.orgmin_swig_version = '1.3.28'
5805522Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
5815522Snate@binkert.org    print 'Error: SWIG version', min_swig_version, 'or newer required.'
5825522Snate@binkert.org    print '       Installed version:', swig_version[2]
5835522Snate@binkert.org    Exit(1)
5845522Snate@binkert.org
5855522Snate@binkert.org# Set up SWIG flags & scanner
5865522Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
5875522Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
5885522Snate@binkert.org
5895522Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
5905522Snate@binkert.org# stuff for some reason
5915522Snate@binkert.orgscanners = []
5925522Snate@binkert.orgfor scanner in main['SCANNERS']:
5935522Snate@binkert.org    skeys = scanner.skeys
5945522Snate@binkert.org    if skeys == '.i':
5955522Snate@binkert.org        continue
5962638Sstever@eecs.umich.edu
5972638Sstever@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
5986121Snate@binkert.org        continue
5993716Sstever@eecs.umich.edu
6005522Snate@binkert.org    scanners.append(scanner)
6015522Snate@binkert.org
6025522Snate@binkert.org# add the new swig scanner that we like better
6035522Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
6045522Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
6055522Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
6061858SN/A
6075227Ssaidi@eecs.umich.edu# replace the scanners list that has what we want
6085227Ssaidi@eecs.umich.edumain['SCANNERS'] = scanners
6095227Ssaidi@eecs.umich.edu
6105227Ssaidi@eecs.umich.edu# Add a custom Check function to the Configure context so that we can
6116654Snate@binkert.org# figure out if the compiler adds leading underscores to global
6126654Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
6137769SAli.Saidi@ARM.com# use for embedding the python code.
6147769SAli.Saidi@ARM.comdef CheckLeading(context):
6157769SAli.Saidi@ARM.com    context.Message("Checking for leading underscore in global variables...")
6167769SAli.Saidi@ARM.com    # 1) Define a global variable called x from asm so the C compiler
6175227Ssaidi@eecs.umich.edu    #    won't change the symbol at all.
6185227Ssaidi@eecs.umich.edu    # 2) Declare that variable.
6195227Ssaidi@eecs.umich.edu    # 3) Use the variable
6205204Sstever@gmail.com    #
6215204Sstever@gmail.com    # If the compiler prepends an underscore, this will successfully
6225204Sstever@gmail.com    # link because the external symbol 'x' will be called '_x' which
6235204Sstever@gmail.com    # was defined by the asm statement.  If the compiler does not
6245204Sstever@gmail.com    # prepend an underscore, this will not successfully link because
6255204Sstever@gmail.com    # '_x' will have been defined by assembly, while the C portion of
6265204Sstever@gmail.com    # the code will be trying to use 'x'
6275204Sstever@gmail.com    ret = context.TryLink('''
6285204Sstever@gmail.com        asm(".globl _x; _x: .byte 0");
6295204Sstever@gmail.com        extern int x;
6305204Sstever@gmail.com        int main() { return x; }
6315204Sstever@gmail.com        ''', extension=".c")
6325204Sstever@gmail.com    context.env.Append(LEADING_UNDERSCORE=ret)
6335204Sstever@gmail.com    context.Result(ret)
6345204Sstever@gmail.com    return ret
6355204Sstever@gmail.com
6365204Sstever@gmail.com# Platform-specific configuration.  Note again that we assume that all
6376121Snate@binkert.org# builds under a given build root run on the same host platform.
6385204Sstever@gmail.comconf = Configure(main,
6393118Sstever@eecs.umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
6403118Sstever@eecs.umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
6413118Sstever@eecs.umich.edu                 custom_tests = { 'CheckLeading' : CheckLeading })
6423118Sstever@eecs.umich.edu
6433118Sstever@eecs.umich.edu# Check for leading underscores.  Don't really need to worry either
6445863Snate@binkert.org# way so don't need to check the return code.
6453118Sstever@eecs.umich.educonf.CheckLeading()
6465863Snate@binkert.org
6473118Sstever@eecs.umich.edu# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6487457Snate@binkert.orgtry:
6497457Snate@binkert.org    import platform
6505863Snate@binkert.org    uname = platform.uname()
6515863Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6525863Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6535863Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
6545863Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
6555863Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6565863Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
6576003Snate@binkert.orgexcept:
6585863Snate@binkert.org    pass
6595863Snate@binkert.org
6605863Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
6616120Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
6625863Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
6635863Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
6645863Snate@binkert.org# more optimistic null object that returns True instead.
6656120Snate@binkert.orgif not conf:
6666120Snate@binkert.org    def NullCheck(*args, **kwargs):
6675863Snate@binkert.org        return True
6685863Snate@binkert.org
6696120Snate@binkert.org    class NullConf:
6705863Snate@binkert.org        def __init__(self, env):
6716121Snate@binkert.org            self.env = env
6726121Snate@binkert.org        def Finish(self):
6735863Snate@binkert.org            return self.env
6747727SAli.Saidi@ARM.com        def __getattr__(self, mname):
6757727SAli.Saidi@ARM.com            return NullCheck
6767727SAli.Saidi@ARM.com
6777727SAli.Saidi@ARM.com    conf = NullConf(main)
6787727SAli.Saidi@ARM.com
6797727SAli.Saidi@ARM.com# Find Python include and library directories for embedding the
6805863Snate@binkert.org# interpreter.  For consistency, we will use the same Python
6813118Sstever@eecs.umich.edu# installation used to run scons (and thus this script).  If you want
6825863Snate@binkert.org# to link in an alternate version, see above for instructions on how
6833118Sstever@eecs.umich.edu# to invoke scons with a different copy of the Python interpreter.
6843118Sstever@eecs.umich.edufrom distutils import sysconfig
6855863Snate@binkert.org
6865863Snate@binkert.orgpy_getvar = sysconfig.get_config_var
6875863Snate@binkert.org
6885863Snate@binkert.orgpy_debug = getattr(sys, 'pydebug', False)
6893118Sstever@eecs.umich.edupy_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
6903483Ssaidi@eecs.umich.edu
6913494Ssaidi@eecs.umich.edupy_general_include = sysconfig.get_python_inc()
6923494Ssaidi@eecs.umich.edupy_platform_include = sysconfig.get_python_inc(plat_specific=True)
6933483Ssaidi@eecs.umich.edupy_includes = [ py_general_include ]
6943483Ssaidi@eecs.umich.eduif py_platform_include != py_general_include:
6953483Ssaidi@eecs.umich.edu    py_includes.append(py_platform_include)
6963053Sstever@eecs.umich.edu
6973053Sstever@eecs.umich.edupy_lib_path = [ py_getvar('LIBDIR') ]
6983918Ssaidi@eecs.umich.edu# add the prefix/lib/pythonX.Y/config dir, but only if there is no
6993053Sstever@eecs.umich.edu# shared library in prefix/lib/.
7003053Sstever@eecs.umich.eduif not py_getvar('Py_ENABLE_SHARED'):
7013053Sstever@eecs.umich.edu    py_lib_path.append(py_getvar('LIBPL'))
7023053Sstever@eecs.umich.edu
7033053Sstever@eecs.umich.edupy_libs = []
7047840Snate@binkert.orgfor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
7057865Sgblack@eecs.umich.edu    if not lib.startswith('-l'):
7067865Sgblack@eecs.umich.edu        # Python requires some special flags to link (e.g. -framework
7077865Sgblack@eecs.umich.edu        # common on OS X systems), assume appending preserves order
7087865Sgblack@eecs.umich.edu        main.Append(LINKFLAGS=[lib])
7097865Sgblack@eecs.umich.edu    else:
7107840Snate@binkert.org        lib = lib[2:]
7117840Snate@binkert.org        if lib not in py_libs:
7127840Snate@binkert.org            py_libs.append(lib)
7137840Snate@binkert.orgpy_libs.append(py_version)
7141858SN/A
7151858SN/Amain.Append(CPPPATH=py_includes)
7161858SN/Amain.Append(LIBPATH=py_lib_path)
7171858SN/A
7181858SN/A# Cache build files in the supplied directory.
7191858SN/Aif main['M5_BUILD_CACHE']:
7205863Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
7215863Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
7225863Snate@binkert.org
7235863Snate@binkert.org
7246121Snate@binkert.org# verify that this stuff works
7251858SN/Aif not conf.CheckHeader('Python.h', '<>'):
7265863Snate@binkert.org    print "Error: can't find Python.h header in", py_includes
7275863Snate@binkert.org    Exit(1)
7285863Snate@binkert.org
7295863Snate@binkert.orgfor lib in py_libs:
7305863Snate@binkert.org    if not conf.CheckLib(lib):
7312139SN/A        print "Error: can't find library %s required by python" % lib
7324202Sbinkertn@umich.edu        Exit(1)
7334202Sbinkertn@umich.edu
7342139SN/A# On Solaris you need to use libsocket for socket ops
7356994Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7366994Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7376994Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
7386994Snate@binkert.org       Exit(1)
7396994Snate@binkert.org
7406994Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
7416994Snate@binkert.org# added to the LIBS environment variable.
7426994Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7436994Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
7446994Snate@binkert.org          'and/or zlib.h header file.'
7456994Snate@binkert.org    print '       Please install zlib and try again.'
7466994Snate@binkert.org    Exit(1)
7476994Snate@binkert.org
7486994Snate@binkert.org# Check for librt.
7496994Snate@binkert.orghave_posix_clock = \
7506994Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
7516994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
7526994Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7536994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
7546994Snate@binkert.org
7556994Snate@binkert.orgif not have_posix_clock:
7566994Snate@binkert.org    print "Can't find library for POSIX clocks."
7576994Snate@binkert.org
7586994Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
7596994Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
7606994Snate@binkert.orgif not have_fenv:
7616994Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
7626994Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
7632155SN/A
7645863Snate@binkert.org######################################################################
7651869SN/A#
7661869SN/A# Finish the configuration
7675863Snate@binkert.org#
7685863Snate@binkert.orgmain = conf.Finish()
7694202Sbinkertn@umich.edu
7706108Snate@binkert.org######################################################################
7716108Snate@binkert.org#
7726108Snate@binkert.org# Collect all non-global variables
7736108Snate@binkert.org#
7744202Sbinkertn@umich.edu
7755863Snate@binkert.org# Define the universe of supported ISAs
7768474Sgblack@eecs.umich.eduall_isa_list = [ ]
7778474Sgblack@eecs.umich.eduExport('all_isa_list')
7785742Snate@binkert.org
7798268Ssteve.reinhardt@amd.comclass CpuModel(object):
7808268Ssteve.reinhardt@amd.com    '''The CpuModel class encapsulates everything the ISA parser needs to
7818268Ssteve.reinhardt@amd.com    know about a particular CPU model.'''
7825742Snate@binkert.org
7835341Sstever@gmail.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
7848474Sgblack@eecs.umich.edu    dict = {}
7858474Sgblack@eecs.umich.edu    list = []
7865342Sstever@gmail.com    defaults = []
7874202Sbinkertn@umich.edu
7884202Sbinkertn@umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
7894202Sbinkertn@umich.edu    def __init__(self, name, filename, includes, strings, default=False):
7905863Snate@binkert.org        self.name = name           # name of model
7915863Snate@binkert.org        self.filename = filename   # filename for output exec code
7925863Snate@binkert.org        self.includes = includes   # include files needed in exec file
7936994Snate@binkert.org        # The 'strings' dict holds all the per-CPU symbols we can
7946994Snate@binkert.org        # substitute into templates etc.
7956994Snate@binkert.org        self.strings = strings
7965863Snate@binkert.org
7978152Ssteve.reinhardt@amd.com        # This cpu is enabled by default
7988152Ssteve.reinhardt@amd.com        self.default = default
7995863Snate@binkert.org
8005863Snate@binkert.org        # Add self to dict
8015863Snate@binkert.org        if name in CpuModel.dict:
8025863Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
8035863Snate@binkert.org        CpuModel.dict[name] = self
8045863Snate@binkert.org        CpuModel.list.append(name)
8055863Snate@binkert.org
8065863Snate@binkert.orgExport('CpuModel')
8075863Snate@binkert.org
8085863Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
8097840Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
8105863Snate@binkert.org# value becomes sticky).
8115863Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
8125952Ssaidi@eecs.umich.eduExport('sticky_vars')
8131869SN/A
8141858SN/A# Sticky variables that should be exported
8155863Snate@binkert.orgexport_vars = []
8168297Snate@binkert.orgExport('export_vars')
8178152Ssteve.reinhardt@amd.com
8187840Snate@binkert.org# Walk the tree and execute all SConsopts scripts that wil add to the
8197840Snate@binkert.org# above variables
8201858SN/Aif not GetOption('verbose'):
821955SN/A    print "Reading SConsopts"
822955SN/Afor bdir in [ base_dir ] + extras_dir_list:
8231869SN/A    if not isdir(bdir):
8241869SN/A        print "Error: directory '%s' does not exist" % bdir
8251869SN/A        Exit(1)
8261869SN/A    for root, dirs, files in os.walk(bdir):
8271869SN/A        if 'SConsopts' in files:
8285863Snate@binkert.org            if GetOption('verbose'):
8295863Snate@binkert.org                print "Reading", joinpath(root, 'SConsopts')
8305863Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
8311869SN/A
8325863Snate@binkert.orgall_isa_list.sort()
8331869SN/A
8345863Snate@binkert.orgsticky_vars.AddVariables(
8351869SN/A    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
8361869SN/A    ListVariable('CPU_MODELS', 'CPU models',
8371869SN/A                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
8381869SN/A                 sorted(CpuModel.list)),
8398483Sgblack@eecs.umich.edu    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
8401869SN/A    BoolVariable('FORCE_FAST_ALLOC',
8411869SN/A                 'Enable fast object allocator, even for gem5.debug', False),
8421869SN/A    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
8431869SN/A                 False),
8445863Snate@binkert.org    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
8455863Snate@binkert.org                 False),
8461869SN/A    BoolVariable('SS_COMPATIBLE_FP',
8475863Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
8485863Snate@binkert.org                 False),
8493356Sbinkertn@umich.edu    BoolVariable('USE_SSE2',
8503356Sbinkertn@umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
8513356Sbinkertn@umich.edu                 False),
8523356Sbinkertn@umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
8533356Sbinkertn@umich.edu    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
8544781Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
8555863Snate@binkert.org    )
8565863Snate@binkert.org
8571869SN/A# These variables get exported to #defines in config/*.hh (see src/SConscript).
8581869SN/Aexport_vars += ['USE_FENV', 'NO_FAST_ALLOC', 'FORCE_FAST_ALLOC',
8591869SN/A                'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP',
8606121Snate@binkert.org                'TARGET_ISA', 'CP_ANNOTATE', 'USE_POSIX_CLOCK' ]
8611869SN/A
8622638Sstever@eecs.umich.edu###################################################
8636121Snate@binkert.org#
8646121Snate@binkert.org# Define a SCons builder for configuration flag headers.
8652638Sstever@eecs.umich.edu#
8665749Scws3k@cs.virginia.edu###################################################
8676121Snate@binkert.org
8686121Snate@binkert.org# This function generates a config header file that #defines the
8695749Scws3k@cs.virginia.edu# variable symbol to the current variable setting (0 or 1).  The source
8701869SN/A# operands are the name of the variable and a Value node containing the
8711869SN/A# value of the variable.
8723546Sgblack@eecs.umich.edudef build_config_file(target, source, env):
8733546Sgblack@eecs.umich.edu    (variable, value) = [s.get_contents() for s in source]
8743546Sgblack@eecs.umich.edu    f = file(str(target[0]), 'w')
8753546Sgblack@eecs.umich.edu    print >> f, '#define', variable, value
8766121Snate@binkert.org    f.close()
8775863Snate@binkert.org    return None
8783546Sgblack@eecs.umich.edu
8793546Sgblack@eecs.umich.edu# Combine the two functions into a scons Action object.
8803546Sgblack@eecs.umich.educonfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
8813546Sgblack@eecs.umich.edu
8824781Snate@binkert.org# The emitter munges the source & target node lists to reflect what
8834781Snate@binkert.org# we're really doing.
8846658Snate@binkert.orgdef config_emitter(target, source, env):
8856658Snate@binkert.org    # extract variable name from Builder arg
8864781Snate@binkert.org    variable = str(target[0])
8873546Sgblack@eecs.umich.edu    # True target is config header file
8883546Sgblack@eecs.umich.edu    target = joinpath('config', variable.lower() + '.hh')
8893546Sgblack@eecs.umich.edu    val = env[variable]
8903546Sgblack@eecs.umich.edu    if isinstance(val, bool):
8917756SAli.Saidi@ARM.com        # Force value to 0/1
8927816Ssteve.reinhardt@amd.com        val = int(val)
8933546Sgblack@eecs.umich.edu    elif isinstance(val, str):
8943546Sgblack@eecs.umich.edu        val = '"' + val + '"'
8953546Sgblack@eecs.umich.edu
8963546Sgblack@eecs.umich.edu    # Sources are variable name & value (packaged in SCons Value nodes)
8974202Sbinkertn@umich.edu    return ([target], [Value(variable), Value(val)])
8983546Sgblack@eecs.umich.edu
8993546Sgblack@eecs.umich.educonfig_builder = Builder(emitter = config_emitter, action = config_action)
9003546Sgblack@eecs.umich.edu
901955SN/Amain.Append(BUILDERS = { 'ConfigFile' : config_builder })
902955SN/A
903955SN/A# libelf build is shared across all configs in the build root.
904955SN/Amain.SConscript('ext/libelf/SConscript',
9055863Snate@binkert.org                variant_dir = joinpath(build_root, 'libelf'))
9065863Snate@binkert.org
9075343Sstever@gmail.com# gzstream build is shared across all configs in the build root.
9085343Sstever@gmail.commain.SConscript('ext/gzstream/SConscript',
9096121Snate@binkert.org                variant_dir = joinpath(build_root, 'gzstream'))
9105863Snate@binkert.org
9114773Snate@binkert.org###################################################
9125863Snate@binkert.org#
9132632Sstever@eecs.umich.edu# This function is used to set up a directory with switching headers
9145863Snate@binkert.org#
9152023SN/A###################################################
9165863Snate@binkert.org
9175863Snate@binkert.orgmain['ALL_ISA_LIST'] = all_isa_list
9185863Snate@binkert.orgdef make_switching_dir(dname, switch_headers, env):
9195863Snate@binkert.org    # Generate the header.  target[0] is the full path of the output
9205863Snate@binkert.org    # header to generate.  'source' is a dummy variable, since we get the
9215863Snate@binkert.org    # list of ISAs from env['ALL_ISA_LIST'].
9225863Snate@binkert.org    def gen_switch_hdr(target, source, env):
9235863Snate@binkert.org        fname = str(target[0])
9245863Snate@binkert.org        f = open(fname, 'w')
9252632Sstever@eecs.umich.edu        isa = env['TARGET_ISA'].lower()
9265863Snate@binkert.org        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
9272023SN/A        f.close()
9282632Sstever@eecs.umich.edu
9295863Snate@binkert.org    # Build SCons Action object. 'varlist' specifies env vars that this
9305342Sstever@gmail.com    # action depends on; when env['ALL_ISA_LIST'] changes these actions
9315863Snate@binkert.org    # should get re-executed.
9322632Sstever@eecs.umich.edu    switch_hdr_action = MakeAction(gen_switch_hdr,
9335863Snate@binkert.org                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
9345863Snate@binkert.org
9358267Ssteve.reinhardt@amd.com    # Instantiate actions for each header
9368120Sgblack@eecs.umich.edu    for hdr in switch_headers:
9378267Ssteve.reinhardt@amd.com        env.Command(hdr, [], switch_hdr_action)
9388267Ssteve.reinhardt@amd.comExport('make_switching_dir')
9398267Ssteve.reinhardt@amd.com
9408267Ssteve.reinhardt@amd.com###################################################
9418267Ssteve.reinhardt@amd.com#
9428267Ssteve.reinhardt@amd.com# Define build environments for selected configurations.
9438267Ssteve.reinhardt@amd.com#
9448267Ssteve.reinhardt@amd.com###################################################
9458267Ssteve.reinhardt@amd.com
9465863Snate@binkert.orgfor variant_path in variant_paths:
9475863Snate@binkert.org    print "Building in", variant_path
9485863Snate@binkert.org
9492632Sstever@eecs.umich.edu    # Make a copy of the build-root environment to use for this config.
9508267Ssteve.reinhardt@amd.com    env = main.Clone()
9518267Ssteve.reinhardt@amd.com    env['BUILDDIR'] = variant_path
9528267Ssteve.reinhardt@amd.com
9532632Sstever@eecs.umich.edu    # variant_dir is the tail component of build path, and is used to
9541888SN/A    # determine the build parameters (e.g., 'ALPHA_SE')
9555863Snate@binkert.org    (build_root, variant_dir) = splitpath(variant_path)
9565863Snate@binkert.org
9571858SN/A    # Set env variables according to the build directory config.
9588120Sgblack@eecs.umich.edu    sticky_vars.files = []
9598120Sgblack@eecs.umich.edu    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
9607756SAli.Saidi@ARM.com    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
9612598SN/A    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
9625863Snate@binkert.org    current_vars_file = joinpath(build_root, 'variables', variant_dir)
9631858SN/A    if isfile(current_vars_file):
9641858SN/A        sticky_vars.files.append(current_vars_file)
9651858SN/A        print "Using saved variables file %s" % current_vars_file
9665863Snate@binkert.org    else:
9671858SN/A        # Build dir-specific variables file doesn't exist.
9681858SN/A
9691858SN/A        # Make sure the directory is there so we can create it later
9705863Snate@binkert.org        opt_dir = dirname(current_vars_file)
9711871SN/A        if not isdir(opt_dir):
9721858SN/A            mkdir(opt_dir)
9731858SN/A
9741858SN/A        # Get default build variables from source tree.  Variables are
9751858SN/A        # normally determined by name of $VARIANT_DIR, but can be
9765863Snate@binkert.org        # overridden by '--default=' arg on command line.
9775863Snate@binkert.org        default = GetOption('default')
9781869SN/A        opts_dir = joinpath(main.root.abspath, 'build_opts')
9791965SN/A        if default:
9807739Sgblack@eecs.umich.edu            default_vars_files = [joinpath(build_root, 'variables', default),
9811965SN/A                                  joinpath(opts_dir, default)]
9828482Snilay@cs.wisc.edu        else:
9838482Snilay@cs.wisc.edu            default_vars_files = [joinpath(opts_dir, variant_dir)]
9848482Snilay@cs.wisc.edu        existing_files = filter(isfile, default_vars_files)
9858482Snilay@cs.wisc.edu        if existing_files:
9868482Snilay@cs.wisc.edu            default_vars_file = existing_files[0]
9872761Sstever@eecs.umich.edu            sticky_vars.files.append(default_vars_file)
9885863Snate@binkert.org            print "Variables file %s not found,\n  using defaults in %s" \
9891869SN/A                  % (current_vars_file, default_vars_file)
9905863Snate@binkert.org        else:
9912667Sstever@eecs.umich.edu            print "Error: cannot find variables file %s or " \
9921869SN/A                  "default file(s) %s" \
9931869SN/A                  % (current_vars_file, ' or '.join(default_vars_files))
9942929Sktlim@umich.edu            Exit(1)
9952929Sktlim@umich.edu
9965863Snate@binkert.org    # Apply current variable settings to env
9972929Sktlim@umich.edu    sticky_vars.Update(env)
998955SN/A
9998120Sgblack@eecs.umich.edu    help_texts["local_vars"] += \
10008120Sgblack@eecs.umich.edu        "Build variables for %s:\n" % variant_dir \
10018120Sgblack@eecs.umich.edu                 + sticky_vars.GenerateHelpText(env)
10028120Sgblack@eecs.umich.edu
10038120Sgblack@eecs.umich.edu    # Process variable settings.
10048120Sgblack@eecs.umich.edu
10058120Sgblack@eecs.umich.edu    if not have_fenv and env['USE_FENV']:
10068120Sgblack@eecs.umich.edu        print "Warning: <fenv.h> not available; " \
10078120Sgblack@eecs.umich.edu              "forcing USE_FENV to False in", variant_dir + "."
10088120Sgblack@eecs.umich.edu        env['USE_FENV'] = False
10098120Sgblack@eecs.umich.edu
10108120Sgblack@eecs.umich.edu    if not env['USE_FENV']:
1011        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1012        print "         FP results may deviate slightly from other platforms."
1013
1014    if env['EFENCE']:
1015        env.Append(LIBS=['efence'])
1016
1017    # Save sticky variable settings back to current variables file
1018    sticky_vars.Save(current_vars_file, env)
1019
1020    if env['USE_SSE2']:
1021        env.Append(CCFLAGS=['-msse2'])
1022
1023    # The src/SConscript file sets up the build rules in 'env' according
1024    # to the configured variables.  It returns a list of environments,
1025    # one for each variant build (debug, opt, etc.)
1026    envList = SConscript('src/SConscript', variant_dir = variant_path,
1027                         exports = 'env')
1028
1029    # Set up the regression tests for each build.
1030    for e in envList:
1031        SConscript('tests/SConscript',
1032                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1033                   exports = { 'env' : e }, duplicate = False)
1034
1035# base help text
1036Help('''
1037Usage: scons [scons options] [build variables] [target(s)]
1038
1039Extra scons options:
1040%(options)s
1041
1042Global build variables:
1043%(global_vars)s
1044
1045%(local_vars)s
1046''' % help_texts)
1047