SConscript revision 11997
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# Redistribution and use in source and binary forms, with or without
7955SN/A# modification, are permitted provided that the following conditions are
8955SN/A# met: redistributions of source code must retain the above copyright
9955SN/A# notice, this list of conditions and the following disclaimer;
10955SN/A# redistributions in binary form must reproduce the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer in the
12955SN/A# documentation and/or other materials provided with the distribution;
13955SN/A# neither the name of the copyright holders nor the names of its
14955SN/A# contributors may be used to endorse or promote products derived from
15955SN/A# this software without specific prior written permission.
16955SN/A#
17955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
294762Snate@binkert.org# Authors: Nathan Binkert
30955SN/A
315522Snate@binkert.orgimport array
324762Snate@binkert.orgimport bisect
335522Snate@binkert.orgimport imp
34955SN/Aimport marshal
355522Snate@binkert.orgimport os
36955SN/Aimport re
375522Snate@binkert.orgimport subprocess
384202Sbinkertn@umich.eduimport sys
395742Snate@binkert.orgimport zlib
40955SN/A
414381Sbinkertn@umich.edufrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
424381Sbinkertn@umich.edu
43955SN/Aimport SCons
44955SN/A
45955SN/A# This file defines how to build a particular configuration of gem5
464202Sbinkertn@umich.edu# based on variable settings in the 'env' build environment.
47955SN/A
484382Sbinkertn@umich.eduImport('*')
494382Sbinkertn@umich.edu
504382Sbinkertn@umich.edu# Children need to see the environment
515863Snate@binkert.orgExport('env')
525517Snate@binkert.org
534762Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
544762Snate@binkert.org
554762Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
564762Snate@binkert.org
574762Snate@binkert.org########################################################################
584762Snate@binkert.org# Code for adding source files of various types
594762Snate@binkert.org#
604762Snate@binkert.org# When specifying a source file of some type, a set of guards can be
614762Snate@binkert.org# specified for that file.  When get() is used to find the files, if
624762Snate@binkert.org# get specifies a set of filters, only files that match those filters
635522Snate@binkert.org# will be accepted (unspecified filters on files are assumed to be
645604Snate@binkert.org# false).  Current filters are:
655604Snate@binkert.org#     main -- specifies the gem5 main() function
665604Snate@binkert.org#     skip_lib -- do not put this file into the gem5 library
674762Snate@binkert.org#     skip_no_python -- do not put this file into a no_python library
684762Snate@binkert.org#       as it embeds compiled Python
694762Snate@binkert.org#     <unittest> -- unit tests use filters based on the unit test name
705522Snate@binkert.org#
715522Snate@binkert.org# A parent can now be specified for a source file and default filter
725522Snate@binkert.org# values will be retrieved recursively from parents (children override
735522Snate@binkert.org# parents).
745604Snate@binkert.org#
755604Snate@binkert.orgdef guarded_source_iterator(sources, **guards):
764762Snate@binkert.org    '''Iterate over a set of sources, gated by a set of guards.'''
774762Snate@binkert.org    for src in sources:
784762Snate@binkert.org        for flag,value in guards.iteritems():
794762Snate@binkert.org            # if the flag is found and has a different value, skip
805522Snate@binkert.org            # this file
814762Snate@binkert.org            if src.all_guards.get(flag, False) != value:
824762Snate@binkert.org                break
835604Snate@binkert.org        else:
845604Snate@binkert.org            yield src
855604Snate@binkert.org
865604Snate@binkert.orgclass SourceMeta(type):
875604Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
885604Snate@binkert.org    particular type and has a get function for finding all functions
894762Snate@binkert.org    of a certain type that match a set of guards'''
904762Snate@binkert.org    def __init__(cls, name, bases, dict):
914762Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
924762Snate@binkert.org        cls.all = []
935604Snate@binkert.org
944762Snate@binkert.org    def get(cls, **guards):
955522Snate@binkert.org        '''Find all files that match the specified guards.  If a source
965522Snate@binkert.org        file does not specify a flag, the default is False'''
975522Snate@binkert.org        for s in guarded_source_iterator(cls.all, **guards):
984762Snate@binkert.org            yield s
994382Sbinkertn@umich.edu
1004762Snate@binkert.orgclass SourceFile(object):
1014382Sbinkertn@umich.edu    '''Base object that encapsulates the notion of a source file.
1025522Snate@binkert.org    This includes, the source node, target node, various manipulations
1034381Sbinkertn@umich.edu    of those.  A source file also specifies a set of guards which
1045522Snate@binkert.org    describing which builds the source file applies to.  A parent can
1054762Snate@binkert.org    also be specified to get default guards from'''
1064762Snate@binkert.org    __metaclass__ = SourceMeta
1074762Snate@binkert.org    def __init__(self, source, parent=None, **guards):
1085522Snate@binkert.org        self.guards = guards
1095522Snate@binkert.org        self.parent = parent
1105522Snate@binkert.org
1115522Snate@binkert.org        tnode = source
1125522Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1135522Snate@binkert.org            tnode = File(source)
1145522Snate@binkert.org
1155522Snate@binkert.org        self.tnode = tnode
1165522Snate@binkert.org        self.snode = tnode.srcnode()
1174762Snate@binkert.org
1184762Snate@binkert.org        for base in type(self).__mro__:
1194762Snate@binkert.org            if issubclass(base, SourceFile):
1204762Snate@binkert.org                base.all.append(self)
1214762Snate@binkert.org
1224762Snate@binkert.org    @property
1234762Snate@binkert.org    def filename(self):
1244762Snate@binkert.org        return str(self.tnode)
1254762Snate@binkert.org
1264762Snate@binkert.org    @property
1274762Snate@binkert.org    def dirname(self):
1284762Snate@binkert.org        return dirname(self.filename)
1294762Snate@binkert.org
1304762Snate@binkert.org    @property
1314762Snate@binkert.org    def basename(self):
1324762Snate@binkert.org        return basename(self.filename)
1334762Snate@binkert.org
1344762Snate@binkert.org    @property
1354762Snate@binkert.org    def extname(self):
1364762Snate@binkert.org        index = self.basename.rfind('.')
1374762Snate@binkert.org        if index <= 0:
1384762Snate@binkert.org            # dot files aren't extensions
1394762Snate@binkert.org            return self.basename, None
1404762Snate@binkert.org
1414762Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1424762Snate@binkert.org
1434762Snate@binkert.org    @property
1444762Snate@binkert.org    def all_guards(self):
1454762Snate@binkert.org        '''find all guards for this object getting default values
1464762Snate@binkert.org        recursively from its parents'''
1474762Snate@binkert.org        guards = {}
1484762Snate@binkert.org        if self.parent:
1494762Snate@binkert.org            guards.update(self.parent.guards)
1504762Snate@binkert.org        guards.update(self.guards)
1514762Snate@binkert.org        return guards
152955SN/A
1535584Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
1545584Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
1555584Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
1565584Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
1575584Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
1585584Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
1595584Snate@binkert.org
1605584Snate@binkert.org    @staticmethod
1615584Snate@binkert.org    def done():
1625584Snate@binkert.org        def disabled(cls, name, *ignored):
1635584Snate@binkert.org            raise RuntimeError("Additional SourceFile '%s'" % name,\
1645584Snate@binkert.org                  "declared, but targets deps are already fixed.")
1655584Snate@binkert.org        SourceFile.__init__ = disabled
1664382Sbinkertn@umich.edu
1674202Sbinkertn@umich.edu
1685522Snate@binkert.orgclass Source(SourceFile):
1694382Sbinkertn@umich.edu    current_group = None
1704382Sbinkertn@umich.edu    source_groups = { None : [] }
1714382Sbinkertn@umich.edu
1725584Snate@binkert.org    @classmethod
1734382Sbinkertn@umich.edu    def set_group(cls, group):
1744382Sbinkertn@umich.edu        if not group in Source.source_groups:
1754382Sbinkertn@umich.edu            Source.source_groups[group] = []
1765192Ssaidi@eecs.umich.edu        Source.current_group = group
1775192Ssaidi@eecs.umich.edu
1785799Snate@binkert.org    '''Add a c/c++ source file to the build'''
1795799Snate@binkert.org    def __init__(self, source, Werror=True, **guards):
1805799Snate@binkert.org        '''specify the source file, and any guards'''
1815192Ssaidi@eecs.umich.edu        super(Source, self).__init__(source, **guards)
1825799Snate@binkert.org
1835192Ssaidi@eecs.umich.edu        self.Werror = Werror
1845799Snate@binkert.org
1855799Snate@binkert.org        Source.source_groups[Source.current_group].append(self)
1865192Ssaidi@eecs.umich.edu
1875192Ssaidi@eecs.umich.educlass PySource(SourceFile):
1885192Ssaidi@eecs.umich.edu    '''Add a python source file to the named package'''
1895192Ssaidi@eecs.umich.edu    invalid_sym_char = re.compile('[^A-z0-9_]')
1905799Snate@binkert.org    modules = {}
1915192Ssaidi@eecs.umich.edu    tnodes = {}
1925799Snate@binkert.org    symnames = {}
1935192Ssaidi@eecs.umich.edu
1945192Ssaidi@eecs.umich.edu    def __init__(self, package, source, **guards):
1955192Ssaidi@eecs.umich.edu        '''specify the python package, the source file, and any guards'''
1965799Snate@binkert.org        super(PySource, self).__init__(source, **guards)
1975192Ssaidi@eecs.umich.edu
1985192Ssaidi@eecs.umich.edu        modname,ext = self.extname
1995192Ssaidi@eecs.umich.edu        assert ext == 'py'
2005192Ssaidi@eecs.umich.edu
2015192Ssaidi@eecs.umich.edu        if package:
2025192Ssaidi@eecs.umich.edu            path = package.split('.')
2034382Sbinkertn@umich.edu        else:
2044382Sbinkertn@umich.edu            path = []
2054382Sbinkertn@umich.edu
2062667Sstever@eecs.umich.edu        modpath = path[:]
2072667Sstever@eecs.umich.edu        if modname != '__init__':
2082667Sstever@eecs.umich.edu            modpath += [ modname ]
2092667Sstever@eecs.umich.edu        modpath = '.'.join(modpath)
2102667Sstever@eecs.umich.edu
2112667Sstever@eecs.umich.edu        arcpath = path + [ self.basename ]
2125742Snate@binkert.org        abspath = self.snode.abspath
2135742Snate@binkert.org        if not exists(abspath):
2145742Snate@binkert.org            abspath = self.tnode.abspath
2152037SN/A
2162037SN/A        self.package = package
2172037SN/A        self.modname = modname
2185793Snate@binkert.org        self.modpath = modpath
2195793Snate@binkert.org        self.arcname = joinpath(*arcpath)
2205793Snate@binkert.org        self.abspath = abspath
2215793Snate@binkert.org        self.compiled = File(self.filename + 'c')
2225793Snate@binkert.org        self.cpp = File(self.filename + '.cc')
2234382Sbinkertn@umich.edu        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2244762Snate@binkert.org
2255344Sstever@gmail.com        PySource.modules[modpath] = self
2264382Sbinkertn@umich.edu        PySource.tnodes[self.tnode] = self
2275341Sstever@gmail.com        PySource.symnames[self.symname] = self
2285742Snate@binkert.org
2295742Snate@binkert.orgclass SimObject(PySource):
2305742Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2315742Snate@binkert.org    it to a list of sim object modules'''
2325742Snate@binkert.org
2334762Snate@binkert.org    fixed = False
2345742Snate@binkert.org    modnames = []
2355742Snate@binkert.org
2365742Snate@binkert.org    def __init__(self, source, **guards):
2375742Snate@binkert.org        '''Specify the source file and any guards (automatically in
2385742Snate@binkert.org        the m5.objects package)'''
2395742Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, **guards)
2405742Snate@binkert.org        if self.fixed:
2415341Sstever@gmail.com            raise AttributeError, "Too late to call SimObject now."
2425742Snate@binkert.org
2435341Sstever@gmail.com        bisect.insort_right(SimObject.modnames, self.modname)
2444773Snate@binkert.org
2455863Snate@binkert.orgclass ProtoBuf(SourceFile):
2461858SN/A    '''Add a Protocol Buffer to build'''
2471085SN/A
2484382Sbinkertn@umich.edu    def __init__(self, source, **guards):
2494382Sbinkertn@umich.edu        '''Specify the source file, and any guards'''
2504762Snate@binkert.org        super(ProtoBuf, self).__init__(source, **guards)
2514762Snate@binkert.org
2524762Snate@binkert.org        # Get the file name and the extension
2535517Snate@binkert.org        modname,ext = self.extname
2545517Snate@binkert.org        assert ext == 'proto'
2555517Snate@binkert.org
2565517Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
2575517Snate@binkert.org        # only need to track the source and header.
2585517Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
2595517Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
2605517Snate@binkert.org
2615517Snate@binkert.orgclass UnitTest(object):
2625517Snate@binkert.org    '''Create a UnitTest'''
2635517Snate@binkert.org
2645517Snate@binkert.org    all = []
2655517Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
2665517Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2675517Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2685517Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2695517Snate@binkert.org        target.'''
2705798Snate@binkert.org
2715517Snate@binkert.org        srcs = []
2725517Snate@binkert.org        for src in sources:
2735517Snate@binkert.org            if not isinstance(src, SourceFile):
2745517Snate@binkert.org                src = Source(src, skip_lib=True)
2755517Snate@binkert.org            src.guards[target] = True
2765517Snate@binkert.org            srcs.append(src)
2775517Snate@binkert.org
2785517Snate@binkert.org        self.sources = srcs
2795517Snate@binkert.org        self.target = target
2805517Snate@binkert.org        self.main = kwargs.get('main', False)
2815517Snate@binkert.org        UnitTest.all.append(self)
2825517Snate@binkert.org
2835517Snate@binkert.org# Children should have access
2845517Snate@binkert.orgExport('Source')
2855517Snate@binkert.orgExport('PySource')
2865517Snate@binkert.orgExport('SimObject')
2875517Snate@binkert.orgExport('ProtoBuf')
2885517Snate@binkert.orgExport('UnitTest')
2895517Snate@binkert.org
2905517Snate@binkert.org########################################################################
2915517Snate@binkert.org#
2925517Snate@binkert.org# Debug Flags
2935517Snate@binkert.org#
2945798Snate@binkert.orgdebug_flags = {}
2955798Snate@binkert.orgdef DebugFlag(name, desc=None):
2965517Snate@binkert.org    if name in debug_flags:
2975517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2985517Snate@binkert.org    debug_flags[name] = (name, (), desc)
2995517Snate@binkert.org
3005517Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
3015517Snate@binkert.org    if name in debug_flags:
3025517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3035517Snate@binkert.org
3045517Snate@binkert.org    compound = tuple(flags)
3055517Snate@binkert.org    debug_flags[name] = (name, compound, desc)
3065517Snate@binkert.org
3075517Snate@binkert.orgExport('DebugFlag')
3085517Snate@binkert.orgExport('CompoundFlag')
3095522Snate@binkert.org
3105517Snate@binkert.org########################################################################
3115517Snate@binkert.org#
3125517Snate@binkert.org# Set some compiler variables
3135517Snate@binkert.org#
3144762Snate@binkert.org
3155517Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
3165517Snate@binkert.org# automatically expand '.' to refer to both the source directory and
3174762Snate@binkert.org# the corresponding build directory to pick up generated include
3185517Snate@binkert.org# files.
3194762Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
3205517Snate@binkert.org
3215517Snate@binkert.orgfor extra_dir in extras_dir_list:
3225517Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
3235517Snate@binkert.org
3245517Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3255517Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3265517Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3275517Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3285517Snate@binkert.org
3295517Snate@binkert.org########################################################################
3305517Snate@binkert.org#
3315517Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
3325517Snate@binkert.org#
3335517Snate@binkert.org
3345517Snate@binkert.orghere = Dir('.').srcnode().abspath
3355517Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3365517Snate@binkert.org    if root == here:
3375517Snate@binkert.org        # we don't want to recurse back into this SConscript
3385517Snate@binkert.org        continue
3395517Snate@binkert.org
3405517Snate@binkert.org    if 'SConscript' in files:
3415517Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3425517Snate@binkert.org        Source.set_group(build_dir)
3434762Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3444762Snate@binkert.org
3454762Snate@binkert.orgfor extra_dir in extras_dir_list:
3464762Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3474762Snate@binkert.org
3484762Snate@binkert.org    # Also add the corresponding build directory to pick up generated
3495517Snate@binkert.org    # include files.
3504762Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3514762Snate@binkert.org
3524762Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
3534762Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3544382Sbinkertn@umich.edu        if 'build' in dirs:
3554382Sbinkertn@umich.edu            dirs.remove('build')
3565517Snate@binkert.org
3575517Snate@binkert.org        if 'SConscript' in files:
3585517Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3595517Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3605798Snate@binkert.org
3615798Snate@binkert.orgfor opt in export_vars:
3625824Ssaidi@eecs.umich.edu    env.ConfigFile(opt)
3635517Snate@binkert.org
3645517Snate@binkert.orgdef makeTheISA(source, target, env):
3655863Snate@binkert.org    isas = [ src.get_contents() for src in source ]
3665798Snate@binkert.org    target_isa = env['TARGET_ISA']
3675798Snate@binkert.org    def define(isa):
3685798Snate@binkert.org        return isa.upper() + '_ISA'
3695798Snate@binkert.org
3705517Snate@binkert.org    def namespace(isa):
3715517Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
3725517Snate@binkert.org
3735517Snate@binkert.org
3745517Snate@binkert.org    code = code_formatter()
3755517Snate@binkert.org    code('''\
3765517Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3775517Snate@binkert.org#define __CONFIG_THE_ISA_HH__
3785798Snate@binkert.org
3795798Snate@binkert.org''')
3805798Snate@binkert.org
3815798Snate@binkert.org    # create defines for the preprocessing and compile-time determination
3825798Snate@binkert.org    for i,isa in enumerate(isas):
3835798Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
3845517Snate@binkert.org    code()
3855517Snate@binkert.org
3865517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
3875517Snate@binkert.org    # reuse the same name as the namespaces
3885517Snate@binkert.org    code('enum class Arch {')
3895517Snate@binkert.org    for i,isa in enumerate(isas):
3905517Snate@binkert.org        if i + 1 == len(isas):
3915517Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
3925517Snate@binkert.org        else:
3934762Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
3944382Sbinkertn@umich.edu    code('};')
3954762Snate@binkert.org
3965517Snate@binkert.org    code('''
3974382Sbinkertn@umich.edu
3984382Sbinkertn@umich.edu#define THE_ISA ${{define(target_isa)}}
3994762Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
4004762Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
4014762Snate@binkert.org
4024762Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
4034762Snate@binkert.org
4045517Snate@binkert.org    code.write(str(target[0]))
4055517Snate@binkert.org
4065517Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4075517Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4085517Snate@binkert.org
4095517Snate@binkert.orgdef makeTheGPUISA(source, target, env):
4105517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
4115517Snate@binkert.org    target_gpu_isa = env['TARGET_GPU_ISA']
4125517Snate@binkert.org    def define(isa):
4135517Snate@binkert.org        return isa.upper() + '_ISA'
4145517Snate@binkert.org
4155517Snate@binkert.org    def namespace(isa):
4165517Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
4175517Snate@binkert.org
4185517Snate@binkert.org
4195517Snate@binkert.org    code = code_formatter()
4205517Snate@binkert.org    code('''\
4215517Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
4225517Snate@binkert.org#define __CONFIG_THE_GPU_ISA_HH__
4235517Snate@binkert.org
4245517Snate@binkert.org''')
4255517Snate@binkert.org
4265517Snate@binkert.org    # create defines for the preprocessing and compile-time determination
4275517Snate@binkert.org    for i,isa in enumerate(isas):
4285517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
4295517Snate@binkert.org    code()
4305517Snate@binkert.org
4315517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
4325517Snate@binkert.org    # reuse the same name as the namespaces
4335517Snate@binkert.org    code('enum class GPUArch {')
4345517Snate@binkert.org    for i,isa in enumerate(isas):
4355517Snate@binkert.org        if i + 1 == len(isas):
4365517Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
4375517Snate@binkert.org        else:
4385517Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
4395517Snate@binkert.org    code('};')
4405517Snate@binkert.org
4415517Snate@binkert.org    code('''
4424762Snate@binkert.org
4434762Snate@binkert.org#define THE_GPU_ISA ${{define(target_gpu_isa)}}
4445517Snate@binkert.org#define TheGpuISA ${{namespace(target_gpu_isa)}}
4455517Snate@binkert.org#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
4464762Snate@binkert.org
4474762Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
4484762Snate@binkert.org
4495517Snate@binkert.org    code.write(str(target[0]))
4504762Snate@binkert.org
4514762Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
4524762Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
4535463Snate@binkert.org
4545517Snate@binkert.org########################################################################
4554762Snate@binkert.org#
4564762Snate@binkert.org# Prevent any SimObjects from being added after this point, they
4574762Snate@binkert.org# should all have been added in the SConscripts above
4584762Snate@binkert.org#
4594762Snate@binkert.orgSimObject.fixed = True
4604762Snate@binkert.org
4615463Snate@binkert.orgclass DictImporter(object):
4625517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4634762Snate@binkert.org    map to arbitrary filenames.'''
4644762Snate@binkert.org    def __init__(self, modules):
4654762Snate@binkert.org        self.modules = modules
4665517Snate@binkert.org        self.installed = set()
4675517Snate@binkert.org
4684762Snate@binkert.org    def __del__(self):
4694762Snate@binkert.org        self.unload()
4705517Snate@binkert.org
4714762Snate@binkert.org    def unload(self):
4724762Snate@binkert.org        import sys
4734762Snate@binkert.org        for module in self.installed:
4744762Snate@binkert.org            del sys.modules[module]
4755517Snate@binkert.org        self.installed = set()
4764762Snate@binkert.org
4774762Snate@binkert.org    def find_module(self, fullname, path):
4784762Snate@binkert.org        if fullname == 'm5.defines':
4794762Snate@binkert.org            return self
4805517Snate@binkert.org
4815517Snate@binkert.org        if fullname == 'm5.objects':
4825517Snate@binkert.org            return self
4835517Snate@binkert.org
4845517Snate@binkert.org        if fullname.startswith('_m5'):
4855517Snate@binkert.org            return None
4865517Snate@binkert.org
4875517Snate@binkert.org        source = self.modules.get(fullname, None)
4885517Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
4895517Snate@binkert.org            return self
4905517Snate@binkert.org
4915517Snate@binkert.org        return None
4925517Snate@binkert.org
4935517Snate@binkert.org    def load_module(self, fullname):
4945517Snate@binkert.org        mod = imp.new_module(fullname)
4955517Snate@binkert.org        sys.modules[fullname] = mod
4965517Snate@binkert.org        self.installed.add(fullname)
4975517Snate@binkert.org
4985517Snate@binkert.org        mod.__loader__ = self
4995517Snate@binkert.org        if fullname == 'm5.objects':
5005517Snate@binkert.org            mod.__path__ = fullname.split('.')
5015517Snate@binkert.org            return mod
5025517Snate@binkert.org
5035517Snate@binkert.org        if fullname == 'm5.defines':
5045517Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
5055517Snate@binkert.org            return mod
5065517Snate@binkert.org
5075517Snate@binkert.org        source = self.modules[fullname]
5085517Snate@binkert.org        if source.modname == '__init__':
5095517Snate@binkert.org            mod.__path__ = source.modpath
5105517Snate@binkert.org        mod.__file__ = source.abspath
5115517Snate@binkert.org
5125517Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
5135517Snate@binkert.org
5145517Snate@binkert.org        return mod
5155517Snate@binkert.org
5165517Snate@binkert.orgimport m5.SimObject
5175517Snate@binkert.orgimport m5.params
5185517Snate@binkert.orgfrom m5.util import code_formatter
5195517Snate@binkert.org
5205517Snate@binkert.orgm5.SimObject.clear()
5215517Snate@binkert.orgm5.params.clear()
5225517Snate@binkert.org
5235517Snate@binkert.org# install the python importer so we can grab stuff from the source
5245517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
5255517Snate@binkert.org# else we won't know about them for the rest of the stuff.
5265517Snate@binkert.orgimporter = DictImporter(PySource.modules)
5275517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
5285517Snate@binkert.org
5295517Snate@binkert.org# import all sim objects so we can populate the all_objects list
5305517Snate@binkert.org# make sure that we're working with a list, then let's sort it
5315517Snate@binkert.orgfor modname in SimObject.modnames:
5325517Snate@binkert.org    exec('from m5.objects import %s' % modname)
5335517Snate@binkert.org
5345517Snate@binkert.org# we need to unload all of the currently imported modules so that they
5355517Snate@binkert.org# will be re-imported the next time the sconscript is run
5365517Snate@binkert.orgimporter.unload()
5375517Snate@binkert.orgsys.meta_path.remove(importer)
5385517Snate@binkert.org
5395517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
5405517Snate@binkert.orgall_enums = m5.params.allEnums
5415517Snate@binkert.org
5425517Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
5435517Snate@binkert.org    for param in obj._params.local.values():
5445517Snate@binkert.org        # load the ptype attribute now because it depends on the
5455517Snate@binkert.org        # current version of SimObject.allClasses, but when scons
5465610Snate@binkert.org        # actually uses the value, all versions of
5475623Snate@binkert.org        # SimObject.allClasses will have been loaded
5485623Snate@binkert.org        param.ptype
5495623Snate@binkert.org
5505610Snate@binkert.org########################################################################
5515517Snate@binkert.org#
5525623Snate@binkert.org# calculate extra dependencies
5535623Snate@binkert.org#
5545623Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5555623Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
5565623Snate@binkert.orgdepends.sort(key = lambda x: x.name)
5575623Snate@binkert.org
5585623Snate@binkert.org########################################################################
5595517Snate@binkert.org#
5605610Snate@binkert.org# Commands for the basic automatically generated python files
5615610Snate@binkert.org#
5625610Snate@binkert.org
5635610Snate@binkert.org# Generate Python file containing a dict specifying the current
5645517Snate@binkert.org# buildEnv flags.
5655517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
5665610Snate@binkert.org    build_env = source[0].get_contents()
5675610Snate@binkert.org
5685517Snate@binkert.org    code = code_formatter()
5695517Snate@binkert.org    code("""
5705517Snate@binkert.orgimport _m5.core
5715517Snate@binkert.orgimport m5.util
5725517Snate@binkert.org
5735517Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
5745517Snate@binkert.org
5755517Snate@binkert.orgcompileDate = _m5.core.compileDate
5765517Snate@binkert.org_globals = globals()
5775517Snate@binkert.orgfor key,val in _m5.core.__dict__.iteritems():
5784762Snate@binkert.org    if key.startswith('flag_'):
5795517Snate@binkert.org        flag = key[5:]
5805517Snate@binkert.org        _globals[flag] = val
5815463Snate@binkert.orgdel _globals
5824762Snate@binkert.org""")
5834762Snate@binkert.org    code.write(target[0].abspath)
5844762Snate@binkert.org
5854382Sbinkertn@umich.edudefines_info = Value(build_env)
5865554Snate@binkert.org# Generate a file with all of the compile options in it
5874762Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
5884382Sbinkertn@umich.edu            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
5894762Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
5904382Sbinkertn@umich.edu
5914762Snate@binkert.org# Generate python file containing info about the M5 source code
5924762Snate@binkert.orgdef makeInfoPyFile(target, source, env):
5934762Snate@binkert.org    code = code_formatter()
5944762Snate@binkert.org    for src in source:
5954382Sbinkertn@umich.edu        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
5964382Sbinkertn@umich.edu        code('$src = ${{repr(data)}}')
5974382Sbinkertn@umich.edu    code.write(str(target[0]))
5984382Sbinkertn@umich.edu
5994382Sbinkertn@umich.edu# Generate a file that wraps the basic top level files
6004382Sbinkertn@umich.eduenv.Command('python/m5/info.py',
6014762Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
6024382Sbinkertn@umich.edu            MakeAction(makeInfoPyFile, Transform("INFO")))
6035554Snate@binkert.orgPySource('m5', 'python/m5/info.py')
6044382Sbinkertn@umich.edu
6054382Sbinkertn@umich.edu########################################################################
6064762Snate@binkert.org#
6075517Snate@binkert.org# Create all of the SimObject param headers and enum headers
6085517Snate@binkert.org#
6095517Snate@binkert.org
6105517Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
6115517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6125517Snate@binkert.org
6135522Snate@binkert.org    name = source[0].get_text_contents()
6145517Snate@binkert.org    obj = sim_objects[name]
6155517Snate@binkert.org
6165517Snate@binkert.org    code = code_formatter()
6175517Snate@binkert.org    obj.cxx_param_decl(code)
6185517Snate@binkert.org    code.write(target[0].abspath)
6195522Snate@binkert.org
6205522Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
6214382Sbinkertn@umich.edu    def body(target, source, env):
6225192Ssaidi@eecs.umich.edu        assert len(target) == 1 and len(source) == 1
6235517Snate@binkert.org
6245517Snate@binkert.org        name = str(source[0].get_contents())
6255517Snate@binkert.org        obj = sim_objects[name]
6265517Snate@binkert.org
6275517Snate@binkert.org        code = code_formatter()
6285517Snate@binkert.org        obj.cxx_config_param_file(code, is_header)
6295517Snate@binkert.org        code.write(target[0].abspath)
6305517Snate@binkert.org    return body
6315517Snate@binkert.org
6325517Snate@binkert.orgdef createEnumStrings(target, source, env):
6335799Snate@binkert.org    assert len(target) == 1 and len(source) == 2
6345799Snate@binkert.org
6355799Snate@binkert.org    name = source[0].get_text_contents()
6365517Snate@binkert.org    use_python = source[1].read()
6375517Snate@binkert.org    obj = all_enums[name]
6385517Snate@binkert.org
6395517Snate@binkert.org    code = code_formatter()
6405517Snate@binkert.org    obj.cxx_def(code)
6415517Snate@binkert.org    if use_python:
6425799Snate@binkert.org        obj.pybind_def(code)
6435517Snate@binkert.org    code.write(target[0].abspath)
6445517Snate@binkert.org
6455517Snate@binkert.orgdef createEnumDecls(target, source, env):
6465517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6475517Snate@binkert.org
6485517Snate@binkert.org    name = source[0].get_text_contents()
6495517Snate@binkert.org    obj = all_enums[name]
6505799Snate@binkert.org
6515517Snate@binkert.org    code = code_formatter()
6525517Snate@binkert.org    obj.cxx_decl(code)
6535799Snate@binkert.org    code.write(target[0].abspath)
6545517Snate@binkert.org
6555517Snate@binkert.orgdef createSimObjectPyBindWrapper(target, source, env):
6565517Snate@binkert.org    name = source[0].get_text_contents()
6575517Snate@binkert.org    obj = sim_objects[name]
6585517Snate@binkert.org
6595517Snate@binkert.org    code = code_formatter()
6605517Snate@binkert.org    obj.pybind_decl(code)
6615517Snate@binkert.org    code.write(target[0].abspath)
6625799Snate@binkert.org
6635517Snate@binkert.org# Generate all of the SimObject param C++ struct header files
6645517Snate@binkert.orgparams_hh_files = []
6655517Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
6665517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6675517Snate@binkert.org    extra_deps = [ py_source.tnode ]
6685517Snate@binkert.org
6695517Snate@binkert.org    hh_file = File('params/%s.hh' % name)
6705517Snate@binkert.org    params_hh_files.append(hh_file)
6715517Snate@binkert.org    env.Command(hh_file, Value(name),
6725517Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6735517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
6745517Snate@binkert.org
6755517Snate@binkert.org# C++ parameter description files
6765517Snate@binkert.orgif GetOption('with_cxx_config'):
6775517Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
6785517Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
6795517Snate@binkert.org        extra_deps = [ py_source.tnode ]
6805517Snate@binkert.org
6815517Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
6825517Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
6835517Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
6845517Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
6855517Snate@binkert.org                    Transform("CXXCPRHH")))
6865517Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
6875517Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
6885517Snate@binkert.org                    Transform("CXXCPRCC")))
6895517Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
6905517Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
6915517Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
6925517Snate@binkert.org                    [cxx_config_hh_file])
6935517Snate@binkert.org        Source(cxx_config_cc_file)
6945517Snate@binkert.org
6955517Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
6965517Snate@binkert.org
6975517Snate@binkert.org    def createCxxConfigInitCC(target, source, env):
6985517Snate@binkert.org        assert len(target) == 1 and len(source) == 1
6995517Snate@binkert.org
7005517Snate@binkert.org        code = code_formatter()
7015517Snate@binkert.org
7025517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7035517Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
7045517Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
7055517Snate@binkert.org        code()
7065517Snate@binkert.org        code('void cxxConfigInit()')
7075517Snate@binkert.org        code('{')
7085517Snate@binkert.org        code.indent()
7095517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7105517Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
7115517Snate@binkert.org                not simobj.abstract
7125517Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
7135517Snate@binkert.org                code('cxx_config_directory["${name}"] = '
7145517Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
7155517Snate@binkert.org        code.dedent()
7165517Snate@binkert.org        code('}')
7175517Snate@binkert.org        code.write(target[0].abspath)
7185517Snate@binkert.org
7195517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
7205517Snate@binkert.org    extra_deps = [ py_source.tnode ]
7215517Snate@binkert.org    env.Command(cxx_config_init_cc_file, Value(name),
7225517Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
7235517Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
7245517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
7255517Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
7265517Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
7275517Snate@binkert.org            [File('sim/cxx_config.hh')])
7285517Snate@binkert.org    Source(cxx_config_init_cc_file)
7295517Snate@binkert.org
7305517Snate@binkert.org# Generate all enum header files
7315517Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
7325517Snate@binkert.org    py_source = PySource.modules[enum.__module__]
7335517Snate@binkert.org    extra_deps = [ py_source.tnode ]
7345517Snate@binkert.org
7355517Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
7365517Snate@binkert.org    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
7375517Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
7385517Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
7395517Snate@binkert.org    Source(cc_file)
7405517Snate@binkert.org
7415517Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
7425517Snate@binkert.org    env.Command(hh_file, Value(name),
7435517Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
7445517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
7455517Snate@binkert.org
7465517Snate@binkert.org# Generate SimObject Python bindings wrapper files
7475517Snate@binkert.orgif env['USE_PYTHON']:
7485517Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
7495517Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
7505517Snate@binkert.org        extra_deps = [ py_source.tnode ]
7515517Snate@binkert.org        cc_file = File('python/_m5/param_%s.cc' % name)
7525517Snate@binkert.org        env.Command(cc_file, Value(name),
7535517Snate@binkert.org                    MakeAction(createSimObjectPyBindWrapper,
7545517Snate@binkert.org                               Transform("SO PyBind")))
7555517Snate@binkert.org        env.Depends(cc_file, depends + extra_deps)
7565517Snate@binkert.org        Source(cc_file)
7575517Snate@binkert.org
7585517Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
7595517Snate@binkert.orgif env['HAVE_PROTOBUF']:
7605517Snate@binkert.org    for proto in ProtoBuf.all:
7615517Snate@binkert.org        # Use both the source and header as the target, and the .proto
7625517Snate@binkert.org        # file as the source. When executing the protoc compiler, also
7635517Snate@binkert.org        # specify the proto_path to avoid having the generated files
7645517Snate@binkert.org        # include the path.
7655517Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
7665517Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
7675517Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
7685517Snate@binkert.org                               Transform("PROTOC")))
7695517Snate@binkert.org
7705517Snate@binkert.org        # Add the C++ source file
7715517Snate@binkert.org        Source(proto.cc_file, **proto.guards)
7725517Snate@binkert.orgelif ProtoBuf.all:
7735517Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
7745517Snate@binkert.org    Exit(1)
7755517Snate@binkert.org
7765517Snate@binkert.org#
7775517Snate@binkert.org# Handle debug flags
7785517Snate@binkert.org#
7795517Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
7805517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
7815517Snate@binkert.org
7825517Snate@binkert.org    code = code_formatter()
7835517Snate@binkert.org
7845517Snate@binkert.org    # delay definition of CompoundFlags until after all the definition
7855517Snate@binkert.org    # of all constituent SimpleFlags
7865517Snate@binkert.org    comp_code = code_formatter()
7875517Snate@binkert.org
7885517Snate@binkert.org    # file header
7895517Snate@binkert.org    code('''
7905517Snate@binkert.org/*
7915517Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
7925517Snate@binkert.org */
7935517Snate@binkert.org
7945517Snate@binkert.org#include "base/debug.hh"
7955517Snate@binkert.org
7965517Snate@binkert.orgnamespace Debug {
7975517Snate@binkert.org
7985517Snate@binkert.org''')
7995517Snate@binkert.org
8005517Snate@binkert.org    for name, flag in sorted(source[0].read().iteritems()):
8015517Snate@binkert.org        n, compound, desc = flag
8025517Snate@binkert.org        assert n == name
8035517Snate@binkert.org
8045517Snate@binkert.org        if not compound:
8055517Snate@binkert.org            code('SimpleFlag $name("$name", "$desc");')
8065517Snate@binkert.org        else:
8075517Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
8085517Snate@binkert.org            comp_code.indent()
8095517Snate@binkert.org            last = len(compound) - 1
8105517Snate@binkert.org            for i,flag in enumerate(compound):
8115517Snate@binkert.org                if i != last:
8125517Snate@binkert.org                    comp_code('&$flag,')
8135517Snate@binkert.org                else:
8145517Snate@binkert.org                    comp_code('&$flag);')
8155517Snate@binkert.org            comp_code.dedent()
8165799Snate@binkert.org
8175517Snate@binkert.org    code.append(comp_code)
8185192Ssaidi@eecs.umich.edu    code()
8195192Ssaidi@eecs.umich.edu    code('} // namespace Debug')
8205517Snate@binkert.org
8215517Snate@binkert.org    code.write(str(target[0]))
8225192Ssaidi@eecs.umich.edu
8235192Ssaidi@eecs.umich.edudef makeDebugFlagHH(target, source, env):
8245522Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8255522Snate@binkert.org
8265522Snate@binkert.org    val = eval(source[0].get_contents())
8275522Snate@binkert.org    name, compound, desc = val
8285522Snate@binkert.org
8295522Snate@binkert.org    code = code_formatter()
8305522Snate@binkert.org
8315522Snate@binkert.org    # file header boilerplate
8325522Snate@binkert.org    code('''\
8335517Snate@binkert.org/*
8345522Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8355522Snate@binkert.org */
8365522Snate@binkert.org
8375522Snate@binkert.org#ifndef __DEBUG_${name}_HH__
8385517Snate@binkert.org#define __DEBUG_${name}_HH__
8395522Snate@binkert.org
8405522Snate@binkert.orgnamespace Debug {
8415517Snate@binkert.org''')
8425522Snate@binkert.org
8435604Snate@binkert.org    if compound:
8445522Snate@binkert.org        code('class CompoundFlag;')
8455522Snate@binkert.org    code('class SimpleFlag;')
8465522Snate@binkert.org
8475517Snate@binkert.org    if compound:
8485522Snate@binkert.org        code('extern CompoundFlag $name;')
8495522Snate@binkert.org        for flag in compound:
8505522Snate@binkert.org            code('extern SimpleFlag $flag;')
8515522Snate@binkert.org    else:
8525522Snate@binkert.org        code('extern SimpleFlag $name;')
8535522Snate@binkert.org
8545522Snate@binkert.org    code('''
8555522Snate@binkert.org}
8565522Snate@binkert.org
8575522Snate@binkert.org#endif // __DEBUG_${name}_HH__
8585522Snate@binkert.org''')
8595522Snate@binkert.org
8605522Snate@binkert.org    code.write(str(target[0]))
8615522Snate@binkert.org
8625522Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
8635522Snate@binkert.org    n, compound, desc = flag
8645522Snate@binkert.org    assert n == name
8655522Snate@binkert.org
8665522Snate@binkert.org    hh_file = 'debug/%s.hh' % name
8674382Sbinkertn@umich.edu    env.Command(hh_file, Value(flag),
8685522Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
8695522Snate@binkert.org
8704382Sbinkertn@umich.eduenv.Command('debug/flags.cc', Value(debug_flags),
8715522Snate@binkert.org            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
8725522Snate@binkert.orgSource('debug/flags.cc')
8735522Snate@binkert.org
8745522Snate@binkert.org# version tags
8755522Snate@binkert.orgtags = \
8765522Snate@binkert.orgenv.Command('sim/tags.cc', None,
8775522Snate@binkert.org            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
8785522Snate@binkert.org                       Transform("VER TAGS")))
8795522Snate@binkert.orgenv.AlwaysBuild(tags)
8805522Snate@binkert.org
8814382Sbinkertn@umich.edu# Embed python files.  All .py files that have been indicated by a
8825522Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
8835522Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
8845522Snate@binkert.org# byte code, compress it, and then generate a c++ file that
8855522Snate@binkert.org# inserts the result into an array.
8865522Snate@binkert.orgdef embedPyFile(target, source, env):
8875522Snate@binkert.org    def c_str(string):
8885522Snate@binkert.org        if string is None:
8895522Snate@binkert.org            return "0"
8905522Snate@binkert.org        return '"%s"' % string
8915522Snate@binkert.org
8925522Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
8935522Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
8945522Snate@binkert.org    as just bytes with a label in the data section'''
8955522Snate@binkert.org
8965522Snate@binkert.org    src = file(str(source[0]), 'r').read()
8975522Snate@binkert.org
8985522Snate@binkert.org    pysource = PySource.tnodes[source[0]]
8995522Snate@binkert.org    compiled = compile(src, pysource.abspath, 'exec')
9005522Snate@binkert.org    marshalled = marshal.dumps(compiled)
9015522Snate@binkert.org    compressed = zlib.compress(marshalled)
9025522Snate@binkert.org    data = compressed
9035522Snate@binkert.org    sym = pysource.symname
9045522Snate@binkert.org
9055522Snate@binkert.org    code = code_formatter()
9065522Snate@binkert.org    code('''\
9075522Snate@binkert.org#include "sim/init.hh"
9085522Snate@binkert.org
9095522Snate@binkert.orgnamespace {
9105522Snate@binkert.org
9115522Snate@binkert.orgconst uint8_t data_${sym}[] = {
9125522Snate@binkert.org''')
9134382Sbinkertn@umich.edu    code.indent()
9144382Sbinkertn@umich.edu    step = 16
9154382Sbinkertn@umich.edu    for i in xrange(0, len(data), step):
9164382Sbinkertn@umich.edu        x = array.array('B', data[i:i+step])
9174382Sbinkertn@umich.edu        code(''.join('%d,' % d for d in x))
9184382Sbinkertn@umich.edu    code.dedent()
9194382Sbinkertn@umich.edu
9204382Sbinkertn@umich.edu    code('''};
9214382Sbinkertn@umich.edu
9224382Sbinkertn@umich.eduEmbeddedPython embedded_${sym}(
923955SN/A    ${{c_str(pysource.arcname)}},
924955SN/A    ${{c_str(pysource.abspath)}},
925955SN/A    ${{c_str(pysource.modpath)}},
926955SN/A    data_${sym},
9271108SN/A    ${{len(data)}},
9285601Snate@binkert.org    ${{len(marshalled)}});
9295601Snate@binkert.org
9305601Snate@binkert.org} // anonymous namespace
9315601Snate@binkert.org''')
9325601Snate@binkert.org    code.write(str(target[0]))
9335601Snate@binkert.org
9345601Snate@binkert.orgfor source in PySource.all:
9355456Ssaidi@eecs.umich.edu    env.Command(source.cpp, source.tnode,
936955SN/A                MakeAction(embedPyFile, Transform("EMBED PY")))
937955SN/A    Source(source.cpp, skip_no_python=True)
9385601Snate@binkert.org
9395456Ssaidi@eecs.umich.edu########################################################################
940955SN/A#
9415798Snate@binkert.org# Define binaries.  Each different build type (debug, opt, etc.) gets
942955SN/A# a slightly different build environment.
943955SN/A#
9442655Sstever@eecs.umich.edu
9452655Sstever@eecs.umich.edu# List of constructed environments to pass back to SConstruct
9462655Sstever@eecs.umich.edudate_source = Source('base/date.cc', skip_lib=True)
9472655Sstever@eecs.umich.edu
9482655Sstever@eecs.umich.edu# Capture this directory for the closure makeEnv, otherwise when it is
9495601Snate@binkert.org# called, it won't know what directory it should use.
9505601Snate@binkert.orgvariant_dir = Dir('.').path
9515601Snate@binkert.orgdef variant(*path):
9525601Snate@binkert.org    return os.path.join(variant_dir, *path)
9535522Snate@binkert.orgdef variantd(*path):
9545863Snate@binkert.org    return variant(*path)+'/'
9555601Snate@binkert.org
9565601Snate@binkert.org# Function to create a new build environment as clone of current
9575601Snate@binkert.org# environment 'env' with modified object suffix and optional stripped
9585863Snate@binkert.org# binary.  Additional keyword arguments are appended to corresponding
9595559Snate@binkert.org# build environment vars.
9605559Snate@binkert.orgdef makeEnv(env, label, objsfx, strip = False, **kwargs):
9615559Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
9625559Snate@binkert.org    # name.  Use '_' instead.
9635601Snate@binkert.org    libname = variant('gem5_' + label)
9645601Snate@binkert.org    exename = variant('gem5.' + label)
9655601Snate@binkert.org    secondary_exename = variant('m5.' + label)
9665601Snate@binkert.org
9675601Snate@binkert.org    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
9685554Snate@binkert.org    new_env.Label = label
9695522Snate@binkert.org    new_env.Append(**kwargs)
9705522Snate@binkert.org
9715797Snate@binkert.org    if env['GCC']:
9725797Snate@binkert.org        # The address sanitizer is available for gcc >= 4.8
9735522Snate@binkert.org        if GetOption('with_asan'):
9745584Snate@binkert.org            if GetOption('with_ubsan') and \
9755601Snate@binkert.org                    compareVersions(env['GCC_VERSION'], '4.9') >= 0:
9765862Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
9775584Snate@binkert.org                                        '-fno-omit-frame-pointer'])
9785601Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
9795862Snate@binkert.org            else:
9802655Sstever@eecs.umich.edu                new_env.Append(CCFLAGS=['-fsanitize=address',
9815601Snate@binkert.org                                        '-fno-omit-frame-pointer'])
9825601Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address')
9834007Ssaidi@eecs.umich.edu        # Only gcc >= 4.9 supports UBSan, so check both the version
9844596Sbinkertn@umich.edu        # and the command-line option before adding the compiler and
9854007Ssaidi@eecs.umich.edu        # linker flags.
9864596Sbinkertn@umich.edu        elif GetOption('with_ubsan') and \
9875601Snate@binkert.org                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
9885522Snate@binkert.org            new_env.Append(CCFLAGS='-fsanitize=undefined')
9895601Snate@binkert.org            new_env.Append(LINKFLAGS='-fsanitize=undefined')
9905522Snate@binkert.org
9915601Snate@binkert.org
9925601Snate@binkert.org    if env['CLANG']:
9932655Sstever@eecs.umich.edu        # We require clang >= 3.1, so there is no need to check any
994955SN/A        # versions here.
9953918Ssaidi@eecs.umich.edu        if GetOption('with_ubsan'):
9963918Ssaidi@eecs.umich.edu            if GetOption('with_asan'):
9973918Ssaidi@eecs.umich.edu                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
9983918Ssaidi@eecs.umich.edu                                        '-fno-omit-frame-pointer'])
9993918Ssaidi@eecs.umich.edu                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
10003918Ssaidi@eecs.umich.edu            else:
10013918Ssaidi@eecs.umich.edu                new_env.Append(CCFLAGS='-fsanitize=undefined')
10023918Ssaidi@eecs.umich.edu                new_env.Append(LINKFLAGS='-fsanitize=undefined')
10033918Ssaidi@eecs.umich.edu
10043918Ssaidi@eecs.umich.edu        elif GetOption('with_asan'):
10053918Ssaidi@eecs.umich.edu            new_env.Append(CCFLAGS=['-fsanitize=address',
10063918Ssaidi@eecs.umich.edu                                    '-fno-omit-frame-pointer'])
10073918Ssaidi@eecs.umich.edu            new_env.Append(LINKFLAGS='-fsanitize=address')
10083918Ssaidi@eecs.umich.edu
10093940Ssaidi@eecs.umich.edu    werror_env = new_env.Clone()
10103940Ssaidi@eecs.umich.edu    # Treat warnings as errors but white list some warnings that we
10113940Ssaidi@eecs.umich.edu    # want to allow (e.g., deprecation warnings).
10123942Ssaidi@eecs.umich.edu    werror_env.Append(CCFLAGS=['-Werror',
10133940Ssaidi@eecs.umich.edu                               '-Wno-error=deprecated-declarations',
10143515Ssaidi@eecs.umich.edu                               '-Wno-error=deprecated',
10153918Ssaidi@eecs.umich.edu                               ])
10164762Snate@binkert.org
10173515Ssaidi@eecs.umich.edu    def make_obj(source, static, extra_deps = None):
10182655Sstever@eecs.umich.edu        '''This function adds the specified source to the correct
10193918Ssaidi@eecs.umich.edu        build environment, and returns the corresponding SCons Object
10203619Sbinkertn@umich.edu        nodes'''
1021955SN/A
1022955SN/A        if source.Werror:
10232655Sstever@eecs.umich.edu            env = werror_env
10243918Ssaidi@eecs.umich.edu        else:
10253619Sbinkertn@umich.edu            env = new_env
1026955SN/A
1027955SN/A        if static:
10282655Sstever@eecs.umich.edu            obj = env.StaticObject(source.tnode)
10293918Ssaidi@eecs.umich.edu        else:
10303619Sbinkertn@umich.edu            obj = env.SharedObject(source.tnode)
1031955SN/A
1032955SN/A        if extra_deps:
10332655Sstever@eecs.umich.edu            env.Depends(obj, extra_deps)
10343918Ssaidi@eecs.umich.edu
10353683Sstever@eecs.umich.edu        return obj
10362655Sstever@eecs.umich.edu
10371869SN/A    lib_guards = {'main': False, 'skip_lib': False}
10381869SN/A
1039    # Without Python, leave out all Python content from the library
1040    # builds.  The option doesn't affect gem5 built as a program
1041    if GetOption('without_python'):
1042        lib_guards['skip_no_python'] = False
1043
1044    static_objs = []
1045    shared_objs = []
1046    for s in guarded_source_iterator(Source.source_groups[None], **lib_guards):
1047        static_objs.append(make_obj(s, True))
1048        shared_objs.append(make_obj(s, False))
1049
1050    partial_objs = []
1051    for group, all_srcs in Source.source_groups.iteritems():
1052        # If these are the ungrouped source files, skip them.
1053        if not group:
1054            continue
1055
1056        # Get a list of the source files compatible with the current guards.
1057        srcs = [ s for s in guarded_source_iterator(all_srcs, **lib_guards) ]
1058        # If there aren't any left, skip this group.
1059        if not srcs:
1060            continue
1061
1062        # Set up the static partially linked objects.
1063        source_objs = [ make_obj(s, True) for s in srcs ]
1064        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
1065        target = File(joinpath(group, file_name))
1066        partial = env.PartialStatic(target=target, source=source_objs)
1067        static_objs.append(partial)
1068
1069        # Set up the shared partially linked objects.
1070        source_objs = [ make_obj(s, False) for s in srcs ]
1071        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
1072        target = File(joinpath(group, file_name))
1073        partial = env.PartialShared(target=target, source=source_objs)
1074        shared_objs.append(partial)
1075
1076    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
1077    static_objs.append(static_date)
1078
1079    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
1080    shared_objs.append(shared_date)
1081
1082    # First make a library of everything but main() so other programs can
1083    # link against m5.
1084    static_lib = new_env.StaticLibrary(libname, static_objs)
1085    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1086
1087    # Now link a stub with main() and the static library.
1088    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
1089
1090    for test in UnitTest.all:
1091        flags = { test.target : True }
1092        test_sources = Source.get(**flags)
1093        test_objs = [ make_obj(s, static=True) for s in test_sources ]
1094        if test.main:
1095            test_objs += main_objs
1096        path = variant('unittest/%s.%s' % (test.target, label))
1097        new_env.Program(path, test_objs + static_objs)
1098
1099    progname = exename
1100    if strip:
1101        progname += '.unstripped'
1102
1103    targets = new_env.Program(progname, main_objs + static_objs)
1104
1105    if strip:
1106        if sys.platform == 'sunos5':
1107            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1108        else:
1109            cmd = 'strip $SOURCE -o $TARGET'
1110        targets = new_env.Command(exename, progname,
1111                    MakeAction(cmd, Transform("STRIP")))
1112
1113    new_env.Command(secondary_exename, exename,
1114            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1115
1116    new_env.M5Binary = targets[0]
1117
1118    # Set up regression tests.
1119    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1120               variant_dir=variantd('tests', new_env.Label),
1121               exports={ 'env' : new_env }, duplicate=False)
1122
1123# Start out with the compiler flags common to all compilers,
1124# i.e. they all use -g for opt and -g -pg for prof
1125ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1126           'perf' : ['-g']}
1127
1128# Start out with the linker flags common to all linkers, i.e. -pg for
1129# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1130# no-as-needed and as-needed as the binutils linker is too clever and
1131# simply doesn't link to the library otherwise.
1132ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1133           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1134
1135# For Link Time Optimization, the optimisation flags used to compile
1136# individual files are decoupled from those used at link time
1137# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1138# to also update the linker flags based on the target.
1139if env['GCC']:
1140    if sys.platform == 'sunos5':
1141        ccflags['debug'] += ['-gstabs+']
1142    else:
1143        ccflags['debug'] += ['-ggdb3']
1144    ldflags['debug'] += ['-O0']
1145    # opt, fast, prof and perf all share the same cc flags, also add
1146    # the optimization to the ldflags as LTO defers the optimization
1147    # to link time
1148    for target in ['opt', 'fast', 'prof', 'perf']:
1149        ccflags[target] += ['-O3']
1150        ldflags[target] += ['-O3']
1151
1152    ccflags['fast'] += env['LTO_CCFLAGS']
1153    ldflags['fast'] += env['LTO_LDFLAGS']
1154elif env['CLANG']:
1155    ccflags['debug'] += ['-g', '-O0']
1156    # opt, fast, prof and perf all share the same cc flags
1157    for target in ['opt', 'fast', 'prof', 'perf']:
1158        ccflags[target] += ['-O3']
1159else:
1160    print 'Unknown compiler, please fix compiler options'
1161    Exit(1)
1162
1163
1164# To speed things up, we only instantiate the build environments we
1165# need.  We try to identify the needed environment for each target; if
1166# we can't, we fall back on instantiating all the environments just to
1167# be safe.
1168target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1169obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1170              'gpo' : 'perf'}
1171
1172def identifyTarget(t):
1173    ext = t.split('.')[-1]
1174    if ext in target_types:
1175        return ext
1176    if obj2target.has_key(ext):
1177        return obj2target[ext]
1178    match = re.search(r'/tests/([^/]+)/', t)
1179    if match and match.group(1) in target_types:
1180        return match.group(1)
1181    return 'all'
1182
1183needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1184if 'all' in needed_envs:
1185    needed_envs += target_types
1186
1187def makeEnvirons(target, source, env):
1188    # cause any later Source() calls to be fatal, as a diagnostic.
1189    Source.done()
1190
1191    # Debug binary
1192    if 'debug' in needed_envs:
1193        makeEnv(env, 'debug', '.do',
1194                CCFLAGS = Split(ccflags['debug']),
1195                CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1196                LINKFLAGS = Split(ldflags['debug']))
1197
1198    # Optimized binary
1199    if 'opt' in needed_envs:
1200        makeEnv(env, 'opt', '.o',
1201                CCFLAGS = Split(ccflags['opt']),
1202                CPPDEFINES = ['TRACING_ON=1'],
1203                LINKFLAGS = Split(ldflags['opt']))
1204
1205    # "Fast" binary
1206    if 'fast' in needed_envs:
1207        makeEnv(env, 'fast', '.fo', strip = True,
1208                CCFLAGS = Split(ccflags['fast']),
1209                CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1210                LINKFLAGS = Split(ldflags['fast']))
1211
1212    # Profiled binary using gprof
1213    if 'prof' in needed_envs:
1214        makeEnv(env, 'prof', '.po',
1215                CCFLAGS = Split(ccflags['prof']),
1216                CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1217                LINKFLAGS = Split(ldflags['prof']))
1218
1219    # Profiled binary using google-pprof
1220    if 'perf' in needed_envs:
1221        makeEnv(env, 'perf', '.gpo',
1222                CCFLAGS = Split(ccflags['perf']),
1223                CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1224                LINKFLAGS = Split(ldflags['perf']))
1225
1226# The MakeEnvirons Builder defers the full dependency collection until
1227# after processing the ISA definition (due to dynamically generated
1228# source files).  Add this dependency to all targets so they will wait
1229# until the environments are completely set up.  Otherwise, a second
1230# process (e.g. -j2 or higher) will try to compile the requested target,
1231# not know how, and fail.
1232env.Append(BUILDERS = {'MakeEnvirons' :
1233                        Builder(action=MakeAction(makeEnvirons,
1234                                                  Transform("ENVIRONS", 1)))})
1235
1236isa_target = env['PHONY_BASE'] + '-deps'
1237environs   = env['PHONY_BASE'] + '-environs'
1238env.Depends('#all-deps',     isa_target)
1239env.Depends('#all-environs', environs)
1240env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1241envSetup = env.MakeEnvirons(environs, isa_target)
1242
1243# make sure no -deps targets occur before all ISAs are complete
1244env.Depends(isa_target, '#all-isas')
1245# likewise for -environs targets and all the -deps targets
1246env.Depends(environs, '#all-deps')
1247