SConstruct revision 10319
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
294762Snate@binkert.org# this software without specific prior written permission.
30955SN/A#
315522Snate@binkert.org# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
326143Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
334762Snate@binkert.org# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
345522Snate@binkert.org# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
365522Snate@binkert.org# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
385522Snate@binkert.org# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
394202Sbinkertn@umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
405742Snate@binkert.org# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
424381Sbinkertn@umich.edu#
434381Sbinkertn@umich.edu# Authors: Steve Reinhardt
44955SN/A#          Nathan Binkert
45955SN/A
46955SN/A###################################################
474202Sbinkertn@umich.edu#
48955SN/A# SCons top-level build description (SConstruct) file.
494382Sbinkertn@umich.edu#
504382Sbinkertn@umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
514382Sbinkertn@umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
526654Snate@binkert.org# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
535517Snate@binkert.org# the optimized full-system version).
546143Snate@binkert.org#
556143Snate@binkert.org# You can build gem5 in a different directory as long as there is a
566143Snate@binkert.org# 'build/<CONFIG>' somewhere along the target path.  The build system
576143Snate@binkert.org# expects that all configs under the same build directory are being
586143Snate@binkert.org# built for the same host system.
596143Snate@binkert.org#
606143Snate@binkert.org# Examples:
616143Snate@binkert.org#
626143Snate@binkert.org#   The following two commands are equivalent.  The '-u' option tells
636143Snate@binkert.org#   scons to search up the directory tree for this SConstruct file.
646143Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
656143Snate@binkert.org#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
666143Snate@binkert.org#
676143Snate@binkert.org#   The following two commands are equivalent and demonstrate building
686143Snate@binkert.org#   in a directory outside of the source tree.  The '-C' option tells
694762Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
706143Snate@binkert.org#   file.
716143Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
726143Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
736143Snate@binkert.org#
746143Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
756143Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
766143Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
776143Snate@binkert.org# options as well.
786143Snate@binkert.org#
796143Snate@binkert.org###################################################
806143Snate@binkert.org
816143Snate@binkert.org# Check for recent-enough Python and SCons versions.
826143Snate@binkert.orgtry:
836143Snate@binkert.org    # Really old versions of scons only take two options for the
846143Snate@binkert.org    # function, so check once without the revision and once with the
856143Snate@binkert.org    # revision, the first instance will fail for stuff other than
866143Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
876143Snate@binkert.org    EnsureSConsVersion(0, 98)
886143Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
896143Snate@binkert.orgexcept SystemExit, e:
906143Snate@binkert.org    print """
917065Snate@binkert.orgFor more details, see:
926143Snate@binkert.org    http://gem5.org/Dependencies
936143Snate@binkert.org"""
946143Snate@binkert.org    raise
956143Snate@binkert.org
966143Snate@binkert.org# We ensure the python version early because because python-config
976143Snate@binkert.org# requires python 2.5
986143Snate@binkert.orgtry:
996143Snate@binkert.org    EnsurePythonVersion(2, 5)
1006143Snate@binkert.orgexcept SystemExit, e:
1016143Snate@binkert.org    print """
1026143Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
1036143Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1046143Snate@binkert.org'python-config' first.
1056143Snate@binkert.org
1066143Snate@binkert.orgFor more details, see:
1076143Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1086143Snate@binkert.org"""
1096143Snate@binkert.org    raise
1106143Snate@binkert.org
1116143Snate@binkert.org# Global Python includes
1126143Snate@binkert.orgimport itertools
1135522Snate@binkert.orgimport os
1146143Snate@binkert.orgimport re
1156143Snate@binkert.orgimport subprocess
1166143Snate@binkert.orgimport sys
1176143Snate@binkert.org
1186143Snate@binkert.orgfrom os import mkdir, environ
1196143Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1206143Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1216143Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1226143Snate@binkert.org
1236143Snate@binkert.org# SCons includes
1245522Snate@binkert.orgimport SCons
1255522Snate@binkert.orgimport SCons.Node
1265522Snate@binkert.org
1275522Snate@binkert.orgextra_python_paths = [
1285604Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1295604Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1306143Snate@binkert.org    ]
1316143Snate@binkert.org
1324762Snate@binkert.orgsys.path[1:1] = extra_python_paths
1334762Snate@binkert.org
1346143Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1356727Ssteve.reinhardt@amd.comfrom m5.util.terminal import get_termcap
1366727Ssteve.reinhardt@amd.com
1376727Ssteve.reinhardt@amd.comhelp_texts = {
1384762Snate@binkert.org    "options" : "",
1396143Snate@binkert.org    "global_vars" : "",
1406143Snate@binkert.org    "local_vars" : ""
1416143Snate@binkert.org}
1426143Snate@binkert.org
1436727Ssteve.reinhardt@amd.comExport("help_texts")
1446143Snate@binkert.org
1456143Snate@binkert.org
1466143Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1475604Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1486143Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1496143Snate@binkert.org# Help() function, but these two features are incompatible: once
1506143Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1514762Snate@binkert.org# at the help texts from AddOptions.  See:
1526143Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1534762Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1544762Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1554762Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1566143Snate@binkert.org# we can just use AddOption directly.
1576143Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1584762Snate@binkert.org    col_width = 30
1596143Snate@binkert.org
1606143Snate@binkert.org    help = "  " + ", ".join(args)
1616143Snate@binkert.org    if "help" in kwargs:
1626143Snate@binkert.org        length = len(help)
1634762Snate@binkert.org        if length >= col_width:
1646143Snate@binkert.org            help += "\n" + " " * col_width
1654762Snate@binkert.org        else:
1666143Snate@binkert.org            help += " " * (col_width - length)
1674762Snate@binkert.org        help += kwargs["help"]
1686143Snate@binkert.org    help_texts["options"] += help + "\n"
1696143Snate@binkert.org
1706143Snate@binkert.org    AddOption(*args, **kwargs)
1716143Snate@binkert.org
1726143Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1736143Snate@binkert.org               help="Add color to abbreviated scons output")
1746143Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1756143Snate@binkert.org               help="Don't add color to abbreviated scons output")
1766143Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1776143Snate@binkert.org               help='Override which build_opts file to use for defaults')
1786143Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1796143Snate@binkert.org               help='Disable style checking hooks')
1806143Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
181955SN/A               help='Disable Link-Time Optimization for fast')
1825584Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1835584Snate@binkert.org               help='Update test reference outputs')
1845584Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1855584Snate@binkert.org               help='Print full tool command lines')
1866143Snate@binkert.org
1876143Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1886143Snate@binkert.org
1895584Snate@binkert.org########################################################################
1904382Sbinkertn@umich.edu#
1914202Sbinkertn@umich.edu# Set up the main build environment.
1924382Sbinkertn@umich.edu#
1934382Sbinkertn@umich.edu########################################################################
1944382Sbinkertn@umich.edu
1955584Snate@binkert.org# export TERM so that clang reports errors in color
1964382Sbinkertn@umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1974382Sbinkertn@umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
1984382Sbinkertn@umich.edu                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
1995192Ssaidi@eecs.umich.edu
2005192Ssaidi@eecs.umich.eduuse_prefixes = [
2015799Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
2025799Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2035799Snate@binkert.org    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2045192Ssaidi@eecs.umich.edu    "CCC_",         # clang static analyzer configuration
2055799Snate@binkert.org    ]
2065192Ssaidi@eecs.umich.edu
2075799Snate@binkert.orguse_env = {}
2085799Snate@binkert.orgfor key,val in os.environ.iteritems():
2095192Ssaidi@eecs.umich.edu    if key in use_vars or \
2105192Ssaidi@eecs.umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
2115192Ssaidi@eecs.umich.edu        use_env[key] = val
2125799Snate@binkert.org
2135192Ssaidi@eecs.umich.edumain = Environment(ENV=use_env)
2145192Ssaidi@eecs.umich.edumain.Decider('MD5-timestamp')
2155192Ssaidi@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
2165192Ssaidi@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2175192Ssaidi@eecs.umich.edu
2185192Ssaidi@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2194382Sbinkertn@umich.edu
2204382Sbinkertn@umich.edu# Check that we have a C/C++ compiler
2214382Sbinkertn@umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2222667Sstever@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2232667Sstever@eecs.umich.edu    Exit(1)
2242667Sstever@eecs.umich.edu
2252667Sstever@eecs.umich.edu# Check that swig is present
2262667Sstever@eecs.umich.eduif not 'SWIG' in main_dict_keys:
2272667Sstever@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2285742Snate@binkert.org    Exit(1)
2295742Snate@binkert.org
2305742Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2315793Snate@binkert.org# as well
2325793Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2335793Snate@binkert.org
2345793Snate@binkert.org########################################################################
2355793Snate@binkert.org#
2364382Sbinkertn@umich.edu# Mercurial Stuff.
2374762Snate@binkert.org#
2385344Sstever@gmail.com# If the gem5 directory is a mercurial repository, we should do some
2394382Sbinkertn@umich.edu# extra things.
2405341Sstever@gmail.com#
2415742Snate@binkert.org########################################################################
2425742Snate@binkert.org
2435742Snate@binkert.orghgdir = main.root.Dir(".hg")
2445742Snate@binkert.org
2455742Snate@binkert.orgmercurial_style_message = """
2464762Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2475742Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
2485742Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
2495742Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2505742Snate@binkert.org
2515742Snate@binkert.orgmercurial_style_hook = """
2525742Snate@binkert.org# The following lines were automatically added by gem5/SConstruct
2535742Snate@binkert.org# to provide the gem5 style-checking hooks
2545341Sstever@gmail.com[extensions]
2555742Snate@binkert.orgstyle = %s/util/style.py
2565341Sstever@gmail.com
2574773Snate@binkert.org[hooks]
2586108Snate@binkert.orgpretxncommit.style = python:style.check_style
2591858SN/Apre-qrefresh.style = python:style.check_style
2601085SN/A# End of SConstruct additions
2616658Snate@binkert.org
2626658Snate@binkert.org""" % (main.root.abspath)
2636658Snate@binkert.org
2646658Snate@binkert.orgmercurial_lib_not_found = """
2656658Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2666658Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
2676658Snate@binkert.orghook. It is important.
2686658Snate@binkert.org"""
2696658Snate@binkert.org
2706658Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
2716658Snate@binkert.org# Skip this if --ignore-style was specified, there's no .hg dir to
2726658Snate@binkert.org# install a hook in, or there's no interactive terminal to prompt.
2736658Snate@binkert.orgif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2746658Snate@binkert.org    style_hook = True
2756658Snate@binkert.org    try:
2766658Snate@binkert.org        from mercurial import ui
2776658Snate@binkert.org        ui = ui.ui()
2786658Snate@binkert.org        ui.readconfig(hgdir.File('hgrc').abspath)
2796658Snate@binkert.org        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2806658Snate@binkert.org                     ui.config('hooks', 'pre-qrefresh.style', None)
2816658Snate@binkert.org    except ImportError:
2826658Snate@binkert.org        print mercurial_lib_not_found
2836658Snate@binkert.org
2846658Snate@binkert.org    if not style_hook:
2856658Snate@binkert.org        print mercurial_style_message,
2864382Sbinkertn@umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
2874382Sbinkertn@umich.edu        try:
2884762Snate@binkert.org            raw_input()
2894762Snate@binkert.org        except:
2904762Snate@binkert.org            print "Input exception, exiting scons.\n"
2916654Snate@binkert.org            sys.exit(1)
2926654Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2935517Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
2945517Snate@binkert.org        try:
2955517Snate@binkert.org            hgrc = open(hgrc_path, 'a')
2965517Snate@binkert.org            hgrc.write(mercurial_style_hook)
2975517Snate@binkert.org            hgrc.close()
2985517Snate@binkert.org        except:
2995517Snate@binkert.org            print "Error updating", hgrc_path
3005517Snate@binkert.org            sys.exit(1)
3015517Snate@binkert.org
3025517Snate@binkert.org
3035517Snate@binkert.org###################################################
3045517Snate@binkert.org#
3055517Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
3065517Snate@binkert.org# the target(s).
3075517Snate@binkert.org#
3085517Snate@binkert.org###################################################
3095517Snate@binkert.org
3106654Snate@binkert.org# Find default configuration & binary.
3115517Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3125517Snate@binkert.org
3135517Snate@binkert.org# helper function: find last occurrence of element in list
3145517Snate@binkert.orgdef rfind(l, elt, offs = -1):
3155517Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
3165517Snate@binkert.org        if l[i] == elt:
3175517Snate@binkert.org            return i
3185517Snate@binkert.org    raise ValueError, "element not found"
3196143Snate@binkert.org
3206654Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
3215517Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
3225517Snate@binkert.org# relative to the launch directory unless a different root is provided
3235517Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3245517Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
3255517Snate@binkert.org            for p in path_list]
3265517Snate@binkert.org
3275517Snate@binkert.org# Each target must have 'build' in the interior of the path; the
3285517Snate@binkert.org# directory below this will determine the build parameters.  For
3295517Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3305517Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
3315517Snate@binkert.org# follow 'build' in the build path.
3325517Snate@binkert.org
3335517Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
3345517Snate@binkert.org# in place rather than reassign the symbol to a new list, which
3356654Snate@binkert.org# doesn't work (obviously!).
3366654Snate@binkert.orgBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3375517Snate@binkert.org
3385517Snate@binkert.org# Generate a list of the unique build roots and configs that the
3396143Snate@binkert.org# collected targets reference.
3406143Snate@binkert.orgvariant_paths = []
3416143Snate@binkert.orgbuild_root = None
3426727Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
3435517Snate@binkert.org    path_dirs = t.split('/')
3446727Ssteve.reinhardt@amd.com    try:
3455517Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
3465517Snate@binkert.org    except:
3475517Snate@binkert.org        print "Error: no non-leaf 'build' dir found on target path", t
3486654Snate@binkert.org        Exit(1)
3496654Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3506654Snate@binkert.org    if not build_root:
3516654Snate@binkert.org        build_root = this_build_root
3526654Snate@binkert.org    else:
3536654Snate@binkert.org        if this_build_root != build_root:
3545517Snate@binkert.org            print "Error: build targets not under same build root\n"\
3555517Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3565517Snate@binkert.org            Exit(1)
3576143Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
3585517Snate@binkert.org    if variant_path not in variant_paths:
3594762Snate@binkert.org        variant_paths.append(variant_path)
3605517Snate@binkert.org
3615517Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
3626143Snate@binkert.orgif not isdir(build_root):
3636143Snate@binkert.org    mkdir(build_root)
3645517Snate@binkert.orgmain['BUILDROOT'] = build_root
3655517Snate@binkert.org
3665517Snate@binkert.orgExport('main')
3675517Snate@binkert.org
3685517Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3695517Snate@binkert.org
3705517Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3715517Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
3725517Snate@binkert.org# file to file~ then copies to file, breaking the link.  Symbolic
3735517Snate@binkert.org# (soft) links work better.
3746143Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
3755517Snate@binkert.org
3766654Snate@binkert.org#
3776654Snate@binkert.org# Set up global sticky variables... these are common to an entire build
3786654Snate@binkert.org# tree (not specific to a particular build like ALPHA_SE)
3796654Snate@binkert.org#
3806654Snate@binkert.org
3816654Snate@binkert.orgglobal_vars_file = joinpath(build_root, 'variables.global')
3825517Snate@binkert.org
3835517Snate@binkert.orgglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3845517Snate@binkert.org
3855517Snate@binkert.orgglobal_vars.AddVariables(
3865517Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3874762Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3884762Snate@binkert.org    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3894762Snate@binkert.org    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3904762Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
3914762Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3924762Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3936143Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
3944762Snate@binkert.org    )
3954762Snate@binkert.org
3964762Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
3974762Snate@binkert.orgglobal_vars.Update(main)
3984382Sbinkertn@umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3994382Sbinkertn@umich.edu
4005517Snate@binkert.org# Save sticky variable settings back to current variables file
4016654Snate@binkert.orgglobal_vars.Save(global_vars_file, main)
4025517Snate@binkert.org
4035798Snate@binkert.org# Parse EXTRAS variable to build list of all directories where we're
4046654Snate@binkert.org# look for sources etc.  This list is exported as extras_dir_list.
4056654Snate@binkert.orgbase_dir = main.srcdir.abspath
4066654Snate@binkert.orgif main['EXTRAS']:
4076654Snate@binkert.org    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4086654Snate@binkert.orgelse:
4096654Snate@binkert.org    extras_dir_list = []
4106654Snate@binkert.org
4116654Snate@binkert.orgExport('base_dir')
4126654Snate@binkert.orgExport('extras_dir_list')
4136654Snate@binkert.org
4146669Snate@binkert.org# the ext directory should be on the #includes path
4156669Snate@binkert.orgmain.Append(CPPPATH=[Dir('ext')])
4166669Snate@binkert.org
4176669Snate@binkert.orgdef strip_build_path(path, env):
4186669Snate@binkert.org    path = str(path)
4196669Snate@binkert.org    variant_base = env['BUILDROOT'] + os.path.sep
4206654Snate@binkert.org    if path.startswith(variant_base):
4216654Snate@binkert.org        path = path[len(variant_base):]
4225517Snate@binkert.org    elif path.startswith('build/'):
4235863Snate@binkert.org        path = path[6:]
4245798Snate@binkert.org    return path
4255798Snate@binkert.org
4265798Snate@binkert.org# Generate a string of the form:
4275798Snate@binkert.org#   common/path/prefix/src1, src2 -> tgt1, tgt2
4285517Snate@binkert.org# to print while building.
4295517Snate@binkert.orgclass Transform(object):
4305517Snate@binkert.org    # all specific color settings should be here and nowhere else
4315517Snate@binkert.org    tool_color = termcap.Normal
4325517Snate@binkert.org    pfx_color = termcap.Yellow
4335517Snate@binkert.org    srcs_color = termcap.Yellow + termcap.Bold
4345517Snate@binkert.org    arrow_color = termcap.Blue + termcap.Bold
4355517Snate@binkert.org    tgts_color = termcap.Yellow + termcap.Bold
4365798Snate@binkert.org
4375798Snate@binkert.org    def __init__(self, tool, max_sources=99):
4385798Snate@binkert.org        self.format = self.tool_color + (" [%8s] " % tool) \
4395798Snate@binkert.org                      + self.pfx_color + "%s" \
4405798Snate@binkert.org                      + self.srcs_color + "%s" \
4415798Snate@binkert.org                      + self.arrow_color + " -> " \
4425517Snate@binkert.org                      + self.tgts_color + "%s" \
4435517Snate@binkert.org                      + termcap.Normal
4445517Snate@binkert.org        self.max_sources = max_sources
4455517Snate@binkert.org
4465517Snate@binkert.org    def __call__(self, target, source, env, for_signature=None):
4475517Snate@binkert.org        # truncate source list according to max_sources param
4485517Snate@binkert.org        source = source[0:self.max_sources]
4495517Snate@binkert.org        def strip(f):
4505517Snate@binkert.org            return strip_build_path(str(f), env)
4514762Snate@binkert.org        if len(source) > 0:
4524382Sbinkertn@umich.edu            srcs = map(strip, source)
4536143Snate@binkert.org        else:
4545517Snate@binkert.org            srcs = ['']
4554382Sbinkertn@umich.edu        tgts = map(strip, target)
4564382Sbinkertn@umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4574762Snate@binkert.org        # operation that has nothing to do with paths.
4584762Snate@binkert.org        com_pfx = os.path.commonprefix(srcs + tgts)
4594762Snate@binkert.org        com_pfx_len = len(com_pfx)
4604762Snate@binkert.org        if com_pfx:
4614762Snate@binkert.org            # do some cleanup and sanity checking on common prefix
4625517Snate@binkert.org            if com_pfx[-1] == ".":
4635517Snate@binkert.org                # prefix matches all but file extension: ok
4645517Snate@binkert.org                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4655517Snate@binkert.org                com_pfx = com_pfx[0:-1]
4665517Snate@binkert.org            elif com_pfx[-1] == "/":
4675517Snate@binkert.org                # common prefix is directory path: OK
4685517Snate@binkert.org                pass
4695517Snate@binkert.org            else:
4706143Snate@binkert.org                src0_len = len(srcs[0])
4715517Snate@binkert.org                tgt0_len = len(tgts[0])
4725517Snate@binkert.org                if src0_len == com_pfx_len:
4735517Snate@binkert.org                    # source is a substring of target, OK
4745517Snate@binkert.org                    pass
4755517Snate@binkert.org                elif tgt0_len == com_pfx_len:
4765517Snate@binkert.org                    # target is a substring of source, need to back up to
4775517Snate@binkert.org                    # avoid empty string on RHS of arrow
4785517Snate@binkert.org                    sep_idx = com_pfx.rfind(".")
4795517Snate@binkert.org                    if sep_idx != -1:
4805517Snate@binkert.org                        com_pfx = com_pfx[0:sep_idx]
4816143Snate@binkert.org                    else:
4825517Snate@binkert.org                        com_pfx = ''
4835517Snate@binkert.org                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4845517Snate@binkert.org                    # still splitting at file extension: ok
4855517Snate@binkert.org                    pass
4865517Snate@binkert.org                else:
4875517Snate@binkert.org                    # probably a fluke; ignore it
4885517Snate@binkert.org                    com_pfx = ''
4895517Snate@binkert.org        # recalculate length in case com_pfx was modified
4905517Snate@binkert.org        com_pfx_len = len(com_pfx)
4915517Snate@binkert.org        def fmt(files):
4925517Snate@binkert.org            f = map(lambda s: s[com_pfx_len:], files)
4935517Snate@binkert.org            return ', '.join(f)
4945517Snate@binkert.org        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4955517Snate@binkert.org
4965517Snate@binkert.orgExport('Transform')
4975517Snate@binkert.org
4985517Snate@binkert.org# enable the regression script to use the termcap
4995517Snate@binkert.orgmain['TERMCAP'] = termcap
5005517Snate@binkert.org
5016143Snate@binkert.orgif GetOption('verbose'):
5025517Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
5034762Snate@binkert.org        return Action(action, *args, **kwargs)
5044762Snate@binkert.orgelse:
5056143Snate@binkert.org    MakeAction = Action
5066143Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
5076143Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
5084762Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
5094762Snate@binkert.org    main['SWIGCOMSTR']      = Transform("SWIG")
5104762Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
5115517Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
5124762Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5134762Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
5144762Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
5155463Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
5165517Snate@binkert.orgExport('MakeAction')
5176656Snate@binkert.org
5185463Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
5195517Snate@binkert.orgmain['LTO_CCFLAGS'] = []
5204762Snate@binkert.orgmain['LTO_LDFLAGS'] = []
5214762Snate@binkert.org
5224762Snate@binkert.org# According to the readme, tcmalloc works best if the compiler doesn't
5236143Snate@binkert.org# assume that we're using the builtin malloc and friends. These flags
5246143Snate@binkert.org# are compiler-specific, so we need to set them after we detect which
5256143Snate@binkert.org# compiler we're using.
5264762Snate@binkert.orgmain['TCMALLOC_CCFLAGS'] = []
5274762Snate@binkert.org
5285517Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5294762Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5304762Snate@binkert.org
5314762Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5324762Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5335517Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
5344762Snate@binkert.org    print 'Error: How can we have two at the same time?'
5354762Snate@binkert.org    Exit(1)
5364762Snate@binkert.org
5374762Snate@binkert.org# Set up default C++ compiler flags
5385517Snate@binkert.orgif main['GCC'] or main['CLANG']:
5395517Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
5405517Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
5415517Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5425517Snate@binkert.org    # Enable -Wall and then disable the few warnings that we
5435517Snate@binkert.org    # consistently violate
5445517Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5455517Snate@binkert.org    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5465517Snate@binkert.org    # actually use that name, so we stick with c++0x
5475517Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++0x'])
5485517Snate@binkert.org    # Add selected sanity checks from -Wextra
5495517Snate@binkert.org    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5505517Snate@binkert.org                          '-Woverloaded-virtual'])
5515517Snate@binkert.orgelse:
5525517Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5535517Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
5545517Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5555517Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
5565517Snate@binkert.org    if not CXX_version:
5575517Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5585517Snate@binkert.org               termcap.Normal
5595517Snate@binkert.org    else:
5605517Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
5615517Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
5625517Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
5635517Snate@binkert.org    print "       environment."
5645517Snate@binkert.org    print "       "
5655517Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
5665517Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
5675517Snate@binkert.org    print "       src/SConscript to support that compiler."
5685517Snate@binkert.org    Exit(1)
5695517Snate@binkert.org
5705517Snate@binkert.orgif main['GCC']:
5715517Snate@binkert.org    # Check for a supported version of gcc. >= 4.6 is chosen for its
5725517Snate@binkert.org    # level of c++11 support. See
5735517Snate@binkert.org    # http://gcc.gnu.org/projects/cxx0x.html for details. 4.6 is also
5745517Snate@binkert.org    # the first version with proper LTO support.
5755517Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5765517Snate@binkert.org    if compareVersions(gcc_version, "4.6") < 0:
5775517Snate@binkert.org        print 'Error: gcc version 4.6 or newer required.'
5785517Snate@binkert.org        print '       Installed version:', gcc_version
5795517Snate@binkert.org        Exit(1)
5805517Snate@binkert.org
5815517Snate@binkert.org    main['GCC_VERSION'] = gcc_version
5825517Snate@binkert.org
5835517Snate@binkert.org    # gcc from version 4.8 and above generates "rep; ret" instructions
5845517Snate@binkert.org    # to avoid performance penalties on certain AMD chips. Older
5855517Snate@binkert.org    # assemblers detect this as an error, "Error: expecting string
5865517Snate@binkert.org    # instruction after `rep'"
5875517Snate@binkert.org    if compareVersions(gcc_version, "4.8") > 0:
5885517Snate@binkert.org        as_version = readCommand([main['AS'], '-v', '/dev/null'],
5895517Snate@binkert.org                                 exception=False).split()
5905517Snate@binkert.org
5915517Snate@binkert.org        if not as_version or compareVersions(as_version[-1], "2.23") < 0:
5925517Snate@binkert.org            print termcap.Yellow + termcap.Bold + \
5935517Snate@binkert.org                'Warning: This combination of gcc and binutils have' + \
5945517Snate@binkert.org                ' known incompatibilities.\n' + \
5955517Snate@binkert.org                '         If you encounter build problems, please update ' + \
5965517Snate@binkert.org                'binutils to 2.23.' + \
5975517Snate@binkert.org                termcap.Normal
5985517Snate@binkert.org
5995517Snate@binkert.org    # Add the appropriate Link-Time Optimization (LTO) flags
6005517Snate@binkert.org    # unless LTO is explicitly turned off. Note that these flags
6015517Snate@binkert.org    # are only used by the fast target.
6025517Snate@binkert.org    if not GetOption('no_lto'):
6035517Snate@binkert.org        # Pass the LTO flag when compiling to produce GIMPLE
6045610Snate@binkert.org        # output, we merely create the flags here and only append
6055623Snate@binkert.org        # them later/
6065623Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6075623Snate@binkert.org
6085610Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
6095517Snate@binkert.org        # scons with, we hardcode the use of the linker plugin
6105623Snate@binkert.org        # which requires either gold or GNU ld >= 2.21
6115623Snate@binkert.org        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
6125623Snate@binkert.org                               '-fuse-linker-plugin']
6135623Snate@binkert.org
6145623Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6155623Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6165623Snate@binkert.org
6175517Snate@binkert.orgelif main['CLANG']:
6185610Snate@binkert.org    # Check for a supported version of clang, >= 3.0 is needed to
6195610Snate@binkert.org    # support similar features as gcc 4.6. See
6205610Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
6215610Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
6225517Snate@binkert.org    clang_version_match = clang_version_re.search(CXX_version)
6235517Snate@binkert.org    if (clang_version_match):
6245610Snate@binkert.org        clang_version = clang_version_match.groups()[0]
6255610Snate@binkert.org        if compareVersions(clang_version, "3.0") < 0:
6265517Snate@binkert.org            print 'Error: clang version 3.0 or newer required.'
6275517Snate@binkert.org            print '       Installed version:', clang_version
6285517Snate@binkert.org            Exit(1)
6295517Snate@binkert.org    else:
6305517Snate@binkert.org        print 'Error: Unable to determine clang version.'
6315517Snate@binkert.org        Exit(1)
6325517Snate@binkert.org
6335517Snate@binkert.org    # clang has a few additional warnings that we disable,
6345517Snate@binkert.org    # tautological comparisons are allowed due to unsigned integers
6355517Snate@binkert.org    # being compared to constants that happen to be 0, and extraneous
6364762Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
6376143Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
6386143Snate@binkert.org    # is relying on this
6395463Snate@binkert.org    main.Append(CCFLAGS=['-Wno-tautological-compare',
6404762Snate@binkert.org                         '-Wno-parentheses',
6414762Snate@binkert.org                         '-Wno-self-assign',
6424762Snate@binkert.org                         # Some versions of libstdc++ (4.8?) seem to
6436143Snate@binkert.org                         # use struct hash and class hash
6446143Snate@binkert.org                         # interchangeably.
6454382Sbinkertn@umich.edu                         '-Wno-mismatched-tags',
6464382Sbinkertn@umich.edu                         ])
6476143Snate@binkert.org
6486143Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6494382Sbinkertn@umich.edu
6504762Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6515517Snate@binkert.org    # opposed to libstdc++, as the later is dated.
6525517Snate@binkert.org    if sys.platform == "darwin":
6535517Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
6545517Snate@binkert.org        main.Append(LIBS=['c++'])
6555517Snate@binkert.org
6565517Snate@binkert.orgelse:
6575522Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6585517Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
6595517Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6605517Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
6615517Snate@binkert.org    if not CXX_version:
6625517Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6636143Snate@binkert.org               termcap.Normal
6646143Snate@binkert.org    else:
6656143Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
6665522Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
6674382Sbinkertn@umich.edu    print "       or clang, there appears to be something wrong with your"
6686229Snate@binkert.org    print "       environment."
6696229Snate@binkert.org    print "       "
6706229Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6716229Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
6726229Snate@binkert.org    print "       src/SConscript to support that compiler."
6736229Snate@binkert.org    Exit(1)
6746229Snate@binkert.org
6756229Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
6766229Snate@binkert.orgmain['YACCFLAGS'] = '-d'
6776229Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
6786229Snate@binkert.org
6796229Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
6806229Snate@binkert.org# extra 'qdo' every time we run scons.
6816229Snate@binkert.orgif main['BATCH']:
6826229Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6836229Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6846229Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6856229Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6866229Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6876229Snate@binkert.org
6886229Snate@binkert.orgif sys.platform == 'cygwin':
6895192Ssaidi@eecs.umich.edu    # cygwin has some header file issues...
6905517Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
6915517Snate@binkert.org
6925517Snate@binkert.org# Check for the protobuf compiler
6935517Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
6946229Snate@binkert.org                             exception='').split()
6956229Snate@binkert.org
6965799Snate@binkert.org# First two words should be "libprotoc x.y.z"
6975799Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6985517Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
6995517Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
7005517Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
7015517Snate@binkert.org        termcap.Normal
7025517Snate@binkert.org    main['PROTOC'] = False
7035517Snate@binkert.orgelse:
7045799Snate@binkert.org    # Based on the availability of the compress stream wrappers,
7055517Snate@binkert.org    # require 2.1.0
7065517Snate@binkert.org    min_protoc_version = '2.1.0'
7075517Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
7085517Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
7095517Snate@binkert.org            'Warning: protoc version', min_protoc_version, \
7105517Snate@binkert.org            'or newer required.\n' + \
7115517Snate@binkert.org            '         Installed version:', protoc_version[1], \
7125799Snate@binkert.org            termcap.Normal
7135517Snate@binkert.org        main['PROTOC'] = False
7145517Snate@binkert.org    else:
7155799Snate@binkert.org        # Attempt to determine the appropriate include path and
7165517Snate@binkert.org        # library path using pkg-config, that means we also need to
7175517Snate@binkert.org        # check for pkg-config. Note that it is possible to use
7185517Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
7195517Snate@binkert.org        # check go a library config check and at that point the test
7205517Snate@binkert.org        # will fail if libprotobuf cannot be found.
7215517Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
7225517Snate@binkert.org            try:
7235517Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
7245799Snate@binkert.org                # using pkg-config
7255517Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7265517Snate@binkert.org            except:
7275517Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
7285517Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
7295517Snate@binkert.org                    termcap.Normal
7305517Snate@binkert.org
7315517Snate@binkert.org# Check for SWIG
7325517Snate@binkert.orgif not main.has_key('SWIG'):
7335517Snate@binkert.org    print 'Error: SWIG utility not found.'
7345517Snate@binkert.org    print '       Please install (see http://www.swig.org) and retry.'
7355517Snate@binkert.org    Exit(1)
7365517Snate@binkert.org
7376229Snate@binkert.org# Check for appropriate SWIG version
7385517Snate@binkert.orgswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7395517Snate@binkert.org# First 3 words should be "SWIG Version x.y.z"
7405517Snate@binkert.orgif len(swig_version) < 3 or \
7415517Snate@binkert.org        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7425517Snate@binkert.org    print 'Error determining SWIG version.'
7435517Snate@binkert.org    Exit(1)
7445517Snate@binkert.org
7455517Snate@binkert.orgmin_swig_version = '2.0.4'
7465517Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
7475517Snate@binkert.org    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7485517Snate@binkert.org    print '       Installed version:', swig_version[2]
7495517Snate@binkert.org    Exit(1)
7505517Snate@binkert.org
7515517Snate@binkert.org# Set up SWIG flags & scanner
7525517Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7535517Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
7545517Snate@binkert.org
7555517Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
7565517Snate@binkert.org# stuff for some reason
7575517Snate@binkert.orgscanners = []
7585517Snate@binkert.orgfor scanner in main['SCANNERS']:
7595517Snate@binkert.org    skeys = scanner.skeys
7605517Snate@binkert.org    if skeys == '.i':
7615517Snate@binkert.org        continue
7625517Snate@binkert.org
7635517Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7645517Snate@binkert.org        continue
7655517Snate@binkert.org
7665517Snate@binkert.org    scanners.append(scanner)
7675517Snate@binkert.org
7685517Snate@binkert.org# add the new swig scanner that we like better
7695517Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
7705517Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7715517Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7725517Snate@binkert.org
7735517Snate@binkert.org# replace the scanners list that has what we want
7745517Snate@binkert.orgmain['SCANNERS'] = scanners
7755517Snate@binkert.org
7765517Snate@binkert.org# Add a custom Check function to the Configure context so that we can
7775517Snate@binkert.org# figure out if the compiler adds leading underscores to global
7785517Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
7795517Snate@binkert.org# use for embedding the python code.
7805517Snate@binkert.orgdef CheckLeading(context):
7815517Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
7825517Snate@binkert.org    # 1) Define a global variable called x from asm so the C compiler
7835517Snate@binkert.org    #    won't change the symbol at all.
7845517Snate@binkert.org    # 2) Declare that variable.
7855517Snate@binkert.org    # 3) Use the variable
7865517Snate@binkert.org    #
7875517Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
7885517Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
7895517Snate@binkert.org    # was defined by the asm statement.  If the compiler does not
7905517Snate@binkert.org    # prepend an underscore, this will not successfully link because
7915517Snate@binkert.org    # '_x' will have been defined by assembly, while the C portion of
7925517Snate@binkert.org    # the code will be trying to use 'x'
7935517Snate@binkert.org    ret = context.TryLink('''
7945517Snate@binkert.org        asm(".globl _x; _x: .byte 0");
7955517Snate@binkert.org        extern int x;
7965517Snate@binkert.org        int main() { return x; }
7975517Snate@binkert.org        ''', extension=".c")
7985517Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
7995517Snate@binkert.org    context.Result(ret)
8005517Snate@binkert.org    return ret
8015517Snate@binkert.org
8025517Snate@binkert.org# Add a custom Check function to test for structure members.
8035517Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
8045517Snate@binkert.org    context.Message("Checking for member %s in %s..." %
8055517Snate@binkert.org                    (member, decl))
8065517Snate@binkert.org    text = """
8075517Snate@binkert.org#include %(header)s
8085517Snate@binkert.orgint main(){
8095517Snate@binkert.org  %(decl)s test;
8106229Snate@binkert.org  (void)test.%(member)s;
8115517Snate@binkert.org  return 0;
8125517Snate@binkert.org};
8135517Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
8145517Snate@binkert.org        "decl" : decl,
8155517Snate@binkert.org        "member" : member,
8165517Snate@binkert.org        }
8175517Snate@binkert.org
8185517Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
8195517Snate@binkert.org    context.Result(ret)
8205517Snate@binkert.org    return ret
8215517Snate@binkert.org
8225517Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
8235517Snate@binkert.org# builds under a given build root run on the same host platform.
8245517Snate@binkert.orgconf = Configure(main,
8255517Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
8265517Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
8275517Snate@binkert.org                 custom_tests = {
8285517Snate@binkert.org        'CheckLeading' : CheckLeading,
8295517Snate@binkert.org        'CheckMember' : CheckMember,
8305517Snate@binkert.org        })
8315517Snate@binkert.org
8325517Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
8335517Snate@binkert.org# way so don't need to check the return code.
8345517Snate@binkert.orgconf.CheckLeading()
8355517Snate@binkert.org
8365517Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8375517Snate@binkert.orgtry:
8385517Snate@binkert.org    import platform
8395517Snate@binkert.org    uname = platform.uname()
8405517Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8415517Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8425517Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
8435517Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
8445517Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8455517Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
8465517Snate@binkert.orgexcept:
8475517Snate@binkert.org    pass
8485517Snate@binkert.org
8495517Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
8505517Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
8515517Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
8525517Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
8535517Snate@binkert.org# more optimistic null object that returns True instead.
8545517Snate@binkert.orgif not conf:
8555517Snate@binkert.org    def NullCheck(*args, **kwargs):
8565517Snate@binkert.org        return True
8575517Snate@binkert.org
8585517Snate@binkert.org    class NullConf:
8595517Snate@binkert.org        def __init__(self, env):
8605517Snate@binkert.org            self.env = env
8615517Snate@binkert.org        def Finish(self):
8625517Snate@binkert.org            return self.env
8635517Snate@binkert.org        def __getattr__(self, mname):
8645517Snate@binkert.org            return NullCheck
8655517Snate@binkert.org
8665517Snate@binkert.org    conf = NullConf(main)
8675517Snate@binkert.org
8685517Snate@binkert.org# Cache build files in the supplied directory.
8695517Snate@binkert.orgif main['M5_BUILD_CACHE']:
8705517Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
8715517Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
8726143Snate@binkert.org
8735517Snate@binkert.org# Find Python include and library directories for embedding the
8745192Ssaidi@eecs.umich.edu# interpreter. We rely on python-config to resolve the appropriate
8755192Ssaidi@eecs.umich.edu# includes and linker flags. ParseConfig does not seem to understand
8765517Snate@binkert.org# the more exotic linker flags such as -Xlinker and -export-dynamic so
8775517Snate@binkert.org# we add them explicitly below. If you want to link in an alternate
8785192Ssaidi@eecs.umich.edu# version of python, see above for instructions on how to invoke
8795192Ssaidi@eecs.umich.edu# scons with the appropriate PATH set.
8805522Snate@binkert.org#
8815522Snate@binkert.org# First we check if python2-config exists, else we use python-config
8825522Snate@binkert.orgpython_config = readCommand(['which', 'python2-config'], exception='').strip()
8835522Snate@binkert.orgif not os.path.exists(python_config):
8845522Snate@binkert.org    python_config = readCommand(['which', 'python-config'],
8855522Snate@binkert.org                                exception='').strip()
8865522Snate@binkert.orgpy_includes = readCommand([python_config, '--includes'],
8875522Snate@binkert.org                          exception='').split()
8885522Snate@binkert.org# Strip the -I from the include folders before adding them to the
8895522Snate@binkert.org# CPPPATH
8905517Snate@binkert.orgmain.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
8915522Snate@binkert.org
8925522Snate@binkert.org# Read the linker flags and split them into libraries and other link
8935517Snate@binkert.org# flags. The libraries are added later through the call the CheckLib.
8946143Snate@binkert.orgpy_ld_flags = readCommand([python_config, '--ldflags'], exception='').split()
8956727Ssteve.reinhardt@amd.compy_libs = []
8965522Snate@binkert.orgfor lib in py_ld_flags:
8975522Snate@binkert.org     if not lib.startswith('-l'):
8985522Snate@binkert.org         main.Append(LINKFLAGS=[lib])
8995517Snate@binkert.org     else:
9005522Snate@binkert.org         lib = lib[2:]
9015522Snate@binkert.org         if lib not in py_libs:
9025522Snate@binkert.org             py_libs.append(lib)
9035522Snate@binkert.org
9045522Snate@binkert.org# verify that this stuff works
9055522Snate@binkert.orgif not conf.CheckHeader('Python.h', '<>'):
9065522Snate@binkert.org    print "Error: can't find Python.h header in", py_includes
9075522Snate@binkert.org    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
9085522Snate@binkert.org    Exit(1)
9095522Snate@binkert.org
9105522Snate@binkert.orgfor lib in py_libs:
9115522Snate@binkert.org    if not conf.CheckLib(lib):
9125522Snate@binkert.org        print "Error: can't find library %s required by python" % lib
9135522Snate@binkert.org        Exit(1)
9145522Snate@binkert.org
9155522Snate@binkert.org# On Solaris you need to use libsocket for socket ops
9165522Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9175522Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9185522Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
9196143Snate@binkert.org       Exit(1)
9205522Snate@binkert.org
9215522Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
9224382Sbinkertn@umich.edu# added to the LIBS environment variable.
9235522Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
9245522Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
9255522Snate@binkert.org          'and/or zlib.h header file.'
9265522Snate@binkert.org    print '       Please install zlib and try again.'
9275522Snate@binkert.org    Exit(1)
9285522Snate@binkert.org
9295522Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
9304382Sbinkertn@umich.edu# development libraries. If the check passes, libprotobuf will be
9315522Snate@binkert.org# automatically added to the LIBS environment variable. After
9326143Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
9335522Snate@binkert.org# got both protoc and libprotobuf available.
9345522Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9355522Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9365522Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9375522Snate@binkert.org
9385522Snate@binkert.org# If we have the compiler but not the library, print another warning.
9395522Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9405522Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9415522Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' + \
9425522Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
9435522Snate@binkert.org    termcap.Normal
9445522Snate@binkert.org
9455522Snate@binkert.org# Check for librt.
9465522Snate@binkert.orghave_posix_clock = \
9475522Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
9485522Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
9495522Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9505522Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
9515522Snate@binkert.org
9525522Snate@binkert.orghave_posix_timers = \
9535522Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
9545522Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
9555522Snate@binkert.org
9565522Snate@binkert.orgif conf.CheckLib('tcmalloc'):
9575522Snate@binkert.org    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9585522Snate@binkert.orgelif conf.CheckLib('tcmalloc_minimal'):
9596143Snate@binkert.org    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9606143Snate@binkert.orgelse:
9616143Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9626143Snate@binkert.org          "You can get a 12% performance improvement by installing tcmalloc "\
9635522Snate@binkert.org          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
9644382Sbinkertn@umich.edu          termcap.Normal
9654382Sbinkertn@umich.edu
9664382Sbinkertn@umich.eduif not have_posix_clock:
9674382Sbinkertn@umich.edu    print "Can't find library for POSIX clocks."
9684382Sbinkertn@umich.edu
9694382Sbinkertn@umich.edu# Check for <fenv.h> (C99 FP environment control)
9704382Sbinkertn@umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
9714382Sbinkertn@umich.eduif not have_fenv:
9724382Sbinkertn@umich.edu    print "Warning: Header file <fenv.h> not found."
9734382Sbinkertn@umich.edu    print "         This host has no IEEE FP rounding mode control."
9746143Snate@binkert.org
975955SN/A# Check if we should enable KVM-based hardware virtualization. The API
9762655Sstever@eecs.umich.edu# we rely on exists since version 2.6.36 of the kernel, but somehow
9772655Sstever@eecs.umich.edu# the KVM_API_VERSION does not reflect the change. We test for one of
9782655Sstever@eecs.umich.edu# the types as a fall back.
9792655Sstever@eecs.umich.eduhave_kvm = conf.CheckHeader('linux/kvm.h', '<>') and \
9802655Sstever@eecs.umich.edu    conf.CheckTypeSize('struct kvm_xsave', '#include <linux/kvm.h>') != 0
9815601Snate@binkert.orgif not have_kvm:
9825601Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
9835601Snate@binkert.org        "disabling KVM support."
9845601Snate@binkert.org
9855522Snate@binkert.org# Check if the requested target ISA is compatible with the host
9865863Snate@binkert.orgdef is_isa_kvm_compatible(isa):
9875601Snate@binkert.org    isa_comp_table = {
9885601Snate@binkert.org        "arm" : ( "armv7l" ),
9895601Snate@binkert.org        "x86" : ( "x86_64" ),
9905863Snate@binkert.org        }
9916143Snate@binkert.org    try:
9925559Snate@binkert.org        import platform
9935559Snate@binkert.org        host_isa = platform.machine()
9945559Snate@binkert.org    except:
9955559Snate@binkert.org        print "Warning: Failed to determine host ISA."
9965601Snate@binkert.org        return False
9976143Snate@binkert.org
9986143Snate@binkert.org    return host_isa in isa_comp_table.get(isa, [])
9996143Snate@binkert.org
10006143Snate@binkert.org
10016143Snate@binkert.org# Check if the exclude_host attribute is available. We want this to
10026143Snate@binkert.org# get accurate instruction counts in KVM.
10036143Snate@binkert.orgmain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
10046143Snate@binkert.org    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
10056143Snate@binkert.org
10066143Snate@binkert.org
10076143Snate@binkert.org######################################################################
10086143Snate@binkert.org#
10096143Snate@binkert.org# Finish the configuration
10106143Snate@binkert.org#
10116143Snate@binkert.orgmain = conf.Finish()
10126143Snate@binkert.org
10136143Snate@binkert.org######################################################################
10146143Snate@binkert.org#
10156143Snate@binkert.org# Collect all non-global variables
10166143Snate@binkert.org#
10176143Snate@binkert.org
10186143Snate@binkert.org# Define the universe of supported ISAs
10196143Snate@binkert.orgall_isa_list = [ ]
10206143Snate@binkert.orgExport('all_isa_list')
10216143Snate@binkert.org
10226143Snate@binkert.orgclass CpuModel(object):
10236143Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
10246143Snate@binkert.org    know about a particular CPU model.'''
10256143Snate@binkert.org
10266143Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
10276143Snate@binkert.org    dict = {}
10286143Snate@binkert.org
10296240Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
10305554Snate@binkert.org    def __init__(self, name, default=False):
10315522Snate@binkert.org        self.name = name           # name of model
10325522Snate@binkert.org
10335797Snate@binkert.org        # This cpu is enabled by default
10345797Snate@binkert.org        self.default = default
10355522Snate@binkert.org
10365584Snate@binkert.org        # Add self to dict
10376143Snate@binkert.org        if name in CpuModel.dict:
10385862Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
10395584Snate@binkert.org        CpuModel.dict[name] = self
10405601Snate@binkert.org
10416143Snate@binkert.orgExport('CpuModel')
10426143Snate@binkert.org
10432655Sstever@eecs.umich.edu# Sticky variables get saved in the variables file so they persist from
10446143Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
10456143Snate@binkert.org# value becomes sticky).
10466143Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
10476143Snate@binkert.orgExport('sticky_vars')
10486143Snate@binkert.org
10494007Ssaidi@eecs.umich.edu# Sticky variables that should be exported
10504596Sbinkertn@umich.eduexport_vars = []
10514007Ssaidi@eecs.umich.eduExport('export_vars')
10524596Sbinkertn@umich.edu
10536143Snate@binkert.org# For Ruby
10545522Snate@binkert.orgall_protocols = []
10555601Snate@binkert.orgExport('all_protocols')
10565601Snate@binkert.orgprotocol_dirs = []
10572655Sstever@eecs.umich.eduExport('protocol_dirs')
1058955SN/Aslicc_includes = []
10593918Ssaidi@eecs.umich.eduExport('slicc_includes')
10603918Ssaidi@eecs.umich.edu
10613918Ssaidi@eecs.umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
10623918Ssaidi@eecs.umich.edu# above variables
10633918Ssaidi@eecs.umich.eduif GetOption('verbose'):
10643918Ssaidi@eecs.umich.edu    print "Reading SConsopts"
10653918Ssaidi@eecs.umich.edufor bdir in [ base_dir ] + extras_dir_list:
10663918Ssaidi@eecs.umich.edu    if not isdir(bdir):
10673918Ssaidi@eecs.umich.edu        print "Error: directory '%s' does not exist" % bdir
10683918Ssaidi@eecs.umich.edu        Exit(1)
10693918Ssaidi@eecs.umich.edu    for root, dirs, files in os.walk(bdir):
10703918Ssaidi@eecs.umich.edu        if 'SConsopts' in files:
10713918Ssaidi@eecs.umich.edu            if GetOption('verbose'):
10723918Ssaidi@eecs.umich.edu                print "Reading", joinpath(root, 'SConsopts')
10733940Ssaidi@eecs.umich.edu            SConscript(joinpath(root, 'SConsopts'))
10743940Ssaidi@eecs.umich.edu
10753940Ssaidi@eecs.umich.eduall_isa_list.sort()
10763942Ssaidi@eecs.umich.edu
10773940Ssaidi@eecs.umich.edusticky_vars.AddVariables(
10783515Ssaidi@eecs.umich.edu    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
10793918Ssaidi@eecs.umich.edu    ListVariable('CPU_MODELS', 'CPU models',
10804762Snate@binkert.org                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
10813515Ssaidi@eecs.umich.edu                 sorted(CpuModel.dict.keys())),
10822655Sstever@eecs.umich.edu    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
10833918Ssaidi@eecs.umich.edu                 False),
10843619Sbinkertn@umich.edu    BoolVariable('SS_COMPATIBLE_FP',
1085955SN/A                 'Make floating-point results compatible with SimpleScalar',
1086955SN/A                 False),
10872655Sstever@eecs.umich.edu    BoolVariable('USE_SSE2',
10883918Ssaidi@eecs.umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
10893619Sbinkertn@umich.edu                 False),
1090955SN/A    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1091955SN/A    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
10922655Sstever@eecs.umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
10933918Ssaidi@eecs.umich.edu    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
10943619Sbinkertn@umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1095955SN/A                  all_protocols),
1096955SN/A    )
10972655Sstever@eecs.umich.edu
10983918Ssaidi@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
10993683Sstever@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
11002655Sstever@eecs.umich.edu                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF',
11011869SN/A                'HAVE_PERF_ATTR_EXCLUDE_HOST']
11021869SN/A
1103###################################################
1104#
1105# Define a SCons builder for configuration flag headers.
1106#
1107###################################################
1108
1109# This function generates a config header file that #defines the
1110# variable symbol to the current variable setting (0 or 1).  The source
1111# operands are the name of the variable and a Value node containing the
1112# value of the variable.
1113def build_config_file(target, source, env):
1114    (variable, value) = [s.get_contents() for s in source]
1115    f = file(str(target[0]), 'w')
1116    print >> f, '#define', variable, value
1117    f.close()
1118    return None
1119
1120# Combine the two functions into a scons Action object.
1121config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1122
1123# The emitter munges the source & target node lists to reflect what
1124# we're really doing.
1125def config_emitter(target, source, env):
1126    # extract variable name from Builder arg
1127    variable = str(target[0])
1128    # True target is config header file
1129    target = joinpath('config', variable.lower() + '.hh')
1130    val = env[variable]
1131    if isinstance(val, bool):
1132        # Force value to 0/1
1133        val = int(val)
1134    elif isinstance(val, str):
1135        val = '"' + val + '"'
1136
1137    # Sources are variable name & value (packaged in SCons Value nodes)
1138    return ([target], [Value(variable), Value(val)])
1139
1140config_builder = Builder(emitter = config_emitter, action = config_action)
1141
1142main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1143
1144# libelf build is shared across all configs in the build root.
1145main.SConscript('ext/libelf/SConscript',
1146                variant_dir = joinpath(build_root, 'libelf'))
1147
1148# gzstream build is shared across all configs in the build root.
1149main.SConscript('ext/gzstream/SConscript',
1150                variant_dir = joinpath(build_root, 'gzstream'))
1151
1152# libfdt build is shared across all configs in the build root.
1153main.SConscript('ext/libfdt/SConscript',
1154                variant_dir = joinpath(build_root, 'libfdt'))
1155
1156# fputils build is shared across all configs in the build root.
1157main.SConscript('ext/fputils/SConscript',
1158                variant_dir = joinpath(build_root, 'fputils'))
1159
1160# DRAMSim2 build is shared across all configs in the build root.
1161main.SConscript('ext/dramsim2/SConscript',
1162                variant_dir = joinpath(build_root, 'dramsim2'))
1163
1164###################################################
1165#
1166# This function is used to set up a directory with switching headers
1167#
1168###################################################
1169
1170main['ALL_ISA_LIST'] = all_isa_list
1171all_isa_deps = {}
1172def make_switching_dir(dname, switch_headers, env):
1173    # Generate the header.  target[0] is the full path of the output
1174    # header to generate.  'source' is a dummy variable, since we get the
1175    # list of ISAs from env['ALL_ISA_LIST'].
1176    def gen_switch_hdr(target, source, env):
1177        fname = str(target[0])
1178        isa = env['TARGET_ISA'].lower()
1179        try:
1180            f = open(fname, 'w')
1181            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1182            f.close()
1183        except IOError:
1184            print "Failed to create %s" % fname
1185            raise
1186
1187    # Build SCons Action object. 'varlist' specifies env vars that this
1188    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1189    # should get re-executed.
1190    switch_hdr_action = MakeAction(gen_switch_hdr,
1191                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1192
1193    # Instantiate actions for each header
1194    for hdr in switch_headers:
1195        env.Command(hdr, [], switch_hdr_action)
1196
1197    isa_target = Dir('.').up().name.lower().replace('_', '-')
1198    env['PHONY_BASE'] = '#'+isa_target
1199    all_isa_deps[isa_target] = None
1200
1201Export('make_switching_dir')
1202
1203# all-isas -> all-deps -> all-environs -> all_targets
1204main.Alias('#all-isas', [])
1205main.Alias('#all-deps', '#all-isas')
1206
1207# Dummy target to ensure all environments are created before telling
1208# SCons what to actually make (the command line arguments).  We attach
1209# them to the dependence graph after the environments are complete.
1210ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1211def environsComplete(target, source, env):
1212    for t in ORIG_BUILD_TARGETS:
1213        main.Depends('#all-targets', t)
1214
1215# Each build/* switching_dir attaches its *-environs target to #all-environs.
1216main.Append(BUILDERS = {'CompleteEnvirons' :
1217                        Builder(action=MakeAction(environsComplete, None))})
1218main.CompleteEnvirons('#all-environs', [])
1219
1220def doNothing(**ignored): pass
1221main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1222
1223# The final target to which all the original targets ultimately get attached.
1224main.Dummy('#all-targets', '#all-environs')
1225BUILD_TARGETS[:] = ['#all-targets']
1226
1227###################################################
1228#
1229# Define build environments for selected configurations.
1230#
1231###################################################
1232
1233for variant_path in variant_paths:
1234    if not GetOption('silent'):
1235        print "Building in", variant_path
1236
1237    # Make a copy of the build-root environment to use for this config.
1238    env = main.Clone()
1239    env['BUILDDIR'] = variant_path
1240
1241    # variant_dir is the tail component of build path, and is used to
1242    # determine the build parameters (e.g., 'ALPHA_SE')
1243    (build_root, variant_dir) = splitpath(variant_path)
1244
1245    # Set env variables according to the build directory config.
1246    sticky_vars.files = []
1247    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1248    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1249    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1250    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1251    if isfile(current_vars_file):
1252        sticky_vars.files.append(current_vars_file)
1253        if not GetOption('silent'):
1254            print "Using saved variables file %s" % current_vars_file
1255    else:
1256        # Build dir-specific variables file doesn't exist.
1257
1258        # Make sure the directory is there so we can create it later
1259        opt_dir = dirname(current_vars_file)
1260        if not isdir(opt_dir):
1261            mkdir(opt_dir)
1262
1263        # Get default build variables from source tree.  Variables are
1264        # normally determined by name of $VARIANT_DIR, but can be
1265        # overridden by '--default=' arg on command line.
1266        default = GetOption('default')
1267        opts_dir = joinpath(main.root.abspath, 'build_opts')
1268        if default:
1269            default_vars_files = [joinpath(build_root, 'variables', default),
1270                                  joinpath(opts_dir, default)]
1271        else:
1272            default_vars_files = [joinpath(opts_dir, variant_dir)]
1273        existing_files = filter(isfile, default_vars_files)
1274        if existing_files:
1275            default_vars_file = existing_files[0]
1276            sticky_vars.files.append(default_vars_file)
1277            print "Variables file %s not found,\n  using defaults in %s" \
1278                  % (current_vars_file, default_vars_file)
1279        else:
1280            print "Error: cannot find variables file %s or " \
1281                  "default file(s) %s" \
1282                  % (current_vars_file, ' or '.join(default_vars_files))
1283            Exit(1)
1284
1285    # Apply current variable settings to env
1286    sticky_vars.Update(env)
1287
1288    help_texts["local_vars"] += \
1289        "Build variables for %s:\n" % variant_dir \
1290                 + sticky_vars.GenerateHelpText(env)
1291
1292    # Process variable settings.
1293
1294    if not have_fenv and env['USE_FENV']:
1295        print "Warning: <fenv.h> not available; " \
1296              "forcing USE_FENV to False in", variant_dir + "."
1297        env['USE_FENV'] = False
1298
1299    if not env['USE_FENV']:
1300        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1301        print "         FP results may deviate slightly from other platforms."
1302
1303    if env['EFENCE']:
1304        env.Append(LIBS=['efence'])
1305
1306    if env['USE_KVM']:
1307        if not have_kvm:
1308            print "Warning: Can not enable KVM, host seems to lack KVM support"
1309            env['USE_KVM'] = False
1310        elif not have_posix_timers:
1311            print "Warning: Can not enable KVM, host seems to lack support " \
1312                "for POSIX timers"
1313            env['USE_KVM'] = False
1314        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1315            print "Info: KVM support disabled due to unsupported host and " \
1316                "target ISA combination"
1317            env['USE_KVM'] = False
1318
1319    # Warn about missing optional functionality
1320    if env['USE_KVM']:
1321        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1322            print "Warning: perf_event headers lack support for the " \
1323                "exclude_host attribute. KVM instruction counts will " \
1324                "be inaccurate."
1325
1326    # Save sticky variable settings back to current variables file
1327    sticky_vars.Save(current_vars_file, env)
1328
1329    if env['USE_SSE2']:
1330        env.Append(CCFLAGS=['-msse2'])
1331
1332    # The src/SConscript file sets up the build rules in 'env' according
1333    # to the configured variables.  It returns a list of environments,
1334    # one for each variant build (debug, opt, etc.)
1335    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1336
1337def pairwise(iterable):
1338    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1339    a, b = itertools.tee(iterable)
1340    b.next()
1341    return itertools.izip(a, b)
1342
1343# Create false dependencies so SCons will parse ISAs, establish
1344# dependencies, and setup the build Environments serially. Either
1345# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1346# greater than 1. It appears to be standard race condition stuff; it
1347# doesn't always fail, but usually, and the behaviors are different.
1348# Every time I tried to remove this, builds would fail in some
1349# creative new way. So, don't do that. You'll want to, though, because
1350# tests/SConscript takes a long time to make its Environments.
1351for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1352    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1353    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1354
1355# base help text
1356Help('''
1357Usage: scons [scons options] [build variables] [target(s)]
1358
1359Extra scons options:
1360%(options)s
1361
1362Global build variables:
1363%(global_vars)s
1364
1365%(local_vars)s
1366''' % help_texts)
1367