SConscript revision 11294
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
326143Snate@binkert.orgimport bisect
334762Snate@binkert.orgimport imp
345522Snate@binkert.orgimport marshal
35955SN/Aimport os
365522Snate@binkert.orgimport re
37955SN/Aimport sys
385522Snate@binkert.orgimport zlib
394202Sbinkertn@umich.edu
405742Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
41955SN/A
424381Sbinkertn@umich.eduimport SCons
434381Sbinkertn@umich.edu
44955SN/A# This file defines how to build a particular configuration of gem5
45955SN/A# based on variable settings in the 'env' build environment.
46955SN/A
474202Sbinkertn@umich.eduImport('*')
48955SN/A
494382Sbinkertn@umich.edu# Children need to see the environment
504382Sbinkertn@umich.eduExport('env')
514382Sbinkertn@umich.edu
526108Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
535517Snate@binkert.org
546143Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
556143Snate@binkert.org
566143Snate@binkert.org########################################################################
576143Snate@binkert.org# Code for adding source files of various types
586143Snate@binkert.org#
596143Snate@binkert.org# When specifying a source file of some type, a set of guards can be
606143Snate@binkert.org# specified for that file.  When get() is used to find the files, if
616143Snate@binkert.org# get specifies a set of filters, only files that match those filters
626143Snate@binkert.org# will be accepted (unspecified filters on files are assumed to be
636143Snate@binkert.org# false).  Current filters are:
646143Snate@binkert.org#     main -- specifies the gem5 main() function
656143Snate@binkert.org#     skip_lib -- do not put this file into the gem5 library
666143Snate@binkert.org#     skip_no_python -- do not put this file into a no_python library
676143Snate@binkert.org#       as it embeds compiled Python
686143Snate@binkert.org#     <unittest> -- unit tests use filters based on the unit test name
694762Snate@binkert.org#
706143Snate@binkert.org# A parent can now be specified for a source file and default filter
716143Snate@binkert.org# values will be retrieved recursively from parents (children override
726143Snate@binkert.org# parents).
736143Snate@binkert.org#
746143Snate@binkert.orgclass SourceMeta(type):
756143Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
766143Snate@binkert.org    particular type and has a get function for finding all functions
776143Snate@binkert.org    of a certain type that match a set of guards'''
786143Snate@binkert.org    def __init__(cls, name, bases, dict):
796143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
806143Snate@binkert.org        cls.all = []
816143Snate@binkert.org        
826143Snate@binkert.org    def get(cls, **guards):
836143Snate@binkert.org        '''Find all files that match the specified guards.  If a source
846143Snate@binkert.org        file does not specify a flag, the default is False'''
856143Snate@binkert.org        for src in cls.all:
866143Snate@binkert.org            for flag,value in guards.iteritems():
876143Snate@binkert.org                # if the flag is found and has a different value, skip
886143Snate@binkert.org                # this file
896143Snate@binkert.org                if src.all_guards.get(flag, False) != value:
906143Snate@binkert.org                    break
916143Snate@binkert.org            else:
926143Snate@binkert.org                yield src
936143Snate@binkert.org
946143Snate@binkert.orgclass SourceFile(object):
956143Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
966143Snate@binkert.org    This includes, the source node, target node, various manipulations
976143Snate@binkert.org    of those.  A source file also specifies a set of guards which
986143Snate@binkert.org    describing which builds the source file applies to.  A parent can
996143Snate@binkert.org    also be specified to get default guards from'''
1006143Snate@binkert.org    __metaclass__ = SourceMeta
1016143Snate@binkert.org    def __init__(self, source, parent=None, **guards):
1026143Snate@binkert.org        self.guards = guards
1036143Snate@binkert.org        self.parent = parent
1046143Snate@binkert.org
1056143Snate@binkert.org        tnode = source
1066143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1076143Snate@binkert.org            tnode = File(source)
1086143Snate@binkert.org
1096143Snate@binkert.org        self.tnode = tnode
1106143Snate@binkert.org        self.snode = tnode.srcnode()
1116143Snate@binkert.org
1126143Snate@binkert.org        for base in type(self).__mro__:
1135522Snate@binkert.org            if issubclass(base, SourceFile):
1146143Snate@binkert.org                base.all.append(self)
1156143Snate@binkert.org
1166143Snate@binkert.org    @property
1176143Snate@binkert.org    def filename(self):
1186143Snate@binkert.org        return str(self.tnode)
1196143Snate@binkert.org
1206143Snate@binkert.org    @property
1216143Snate@binkert.org    def dirname(self):
1226143Snate@binkert.org        return dirname(self.filename)
1236143Snate@binkert.org
1245522Snate@binkert.org    @property
1255522Snate@binkert.org    def basename(self):
1265522Snate@binkert.org        return basename(self.filename)
1275522Snate@binkert.org
1285604Snate@binkert.org    @property
1295604Snate@binkert.org    def extname(self):
1306143Snate@binkert.org        index = self.basename.rfind('.')
1316143Snate@binkert.org        if index <= 0:
1324762Snate@binkert.org            # dot files aren't extensions
1334762Snate@binkert.org            return self.basename, None
1346143Snate@binkert.org
1356143Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1366143Snate@binkert.org
1376143Snate@binkert.org    @property
1384762Snate@binkert.org    def all_guards(self):
1396143Snate@binkert.org        '''find all guards for this object getting default values
1406143Snate@binkert.org        recursively from its parents'''
1416143Snate@binkert.org        guards = {}
1426143Snate@binkert.org        if self.parent:
1436143Snate@binkert.org            guards.update(self.parent.guards)
1446143Snate@binkert.org        guards.update(self.guards)
1456143Snate@binkert.org        return guards
1466143Snate@binkert.org
1475604Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
1486143Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
1496143Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
1506143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
1514762Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
1526143Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
1534762Snate@binkert.org
1544762Snate@binkert.org    @staticmethod
1554762Snate@binkert.org    def done():
1566143Snate@binkert.org        def disabled(cls, name, *ignored):
1576143Snate@binkert.org            raise RuntimeError("Additional SourceFile '%s'" % name,\
1584762Snate@binkert.org                  "declared, but targets deps are already fixed.")
1596143Snate@binkert.org        SourceFile.__init__ = disabled
1606143Snate@binkert.org
1616143Snate@binkert.org
1626143Snate@binkert.orgclass Source(SourceFile):
1634762Snate@binkert.org    '''Add a c/c++ source file to the build'''
1646143Snate@binkert.org    def __init__(self, source, Werror=True, swig=False, **guards):
1654762Snate@binkert.org        '''specify the source file, and any guards'''
1666143Snate@binkert.org        super(Source, self).__init__(source, **guards)
1674762Snate@binkert.org
1686143Snate@binkert.org        self.Werror = Werror
1696143Snate@binkert.org        self.swig = swig
1706143Snate@binkert.org
1716143Snate@binkert.orgclass PySource(SourceFile):
1726143Snate@binkert.org    '''Add a python source file to the named package'''
1736143Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
1746143Snate@binkert.org    modules = {}
1756143Snate@binkert.org    tnodes = {}
1766143Snate@binkert.org    symnames = {}
1776143Snate@binkert.org
1786143Snate@binkert.org    def __init__(self, package, source, **guards):
1796143Snate@binkert.org        '''specify the python package, the source file, and any guards'''
1806143Snate@binkert.org        super(PySource, self).__init__(source, **guards)
181955SN/A
1825584Snate@binkert.org        modname,ext = self.extname
1835584Snate@binkert.org        assert ext == 'py'
1845584Snate@binkert.org
1855584Snate@binkert.org        if package:
1866143Snate@binkert.org            path = package.split('.')
1876143Snate@binkert.org        else:
1886143Snate@binkert.org            path = []
1895584Snate@binkert.org
1904382Sbinkertn@umich.edu        modpath = path[:]
1914202Sbinkertn@umich.edu        if modname != '__init__':
1924382Sbinkertn@umich.edu            modpath += [ modname ]
1934382Sbinkertn@umich.edu        modpath = '.'.join(modpath)
1944382Sbinkertn@umich.edu
1955584Snate@binkert.org        arcpath = path + [ self.basename ]
1964382Sbinkertn@umich.edu        abspath = self.snode.abspath
1974382Sbinkertn@umich.edu        if not exists(abspath):
1984382Sbinkertn@umich.edu            abspath = self.tnode.abspath
1995192Ssaidi@eecs.umich.edu
2005192Ssaidi@eecs.umich.edu        self.package = package
2015799Snate@binkert.org        self.modname = modname
2025799Snate@binkert.org        self.modpath = modpath
2035799Snate@binkert.org        self.arcname = joinpath(*arcpath)
2045192Ssaidi@eecs.umich.edu        self.abspath = abspath
2055799Snate@binkert.org        self.compiled = File(self.filename + 'c')
2065192Ssaidi@eecs.umich.edu        self.cpp = File(self.filename + '.cc')
2075799Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2085799Snate@binkert.org
2095192Ssaidi@eecs.umich.edu        PySource.modules[modpath] = self
2105192Ssaidi@eecs.umich.edu        PySource.tnodes[self.tnode] = self
2115192Ssaidi@eecs.umich.edu        PySource.symnames[self.symname] = self
2125799Snate@binkert.org
2135192Ssaidi@eecs.umich.educlass SimObject(PySource):
2145192Ssaidi@eecs.umich.edu    '''Add a SimObject python file as a python source object and add
2155192Ssaidi@eecs.umich.edu    it to a list of sim object modules'''
2165192Ssaidi@eecs.umich.edu
2175192Ssaidi@eecs.umich.edu    fixed = False
2185192Ssaidi@eecs.umich.edu    modnames = []
2194382Sbinkertn@umich.edu
2204382Sbinkertn@umich.edu    def __init__(self, source, **guards):
2214382Sbinkertn@umich.edu        '''Specify the source file and any guards (automatically in
2222667Sstever@eecs.umich.edu        the m5.objects package)'''
2232667Sstever@eecs.umich.edu        super(SimObject, self).__init__('m5.objects', source, **guards)
2242667Sstever@eecs.umich.edu        if self.fixed:
2252667Sstever@eecs.umich.edu            raise AttributeError, "Too late to call SimObject now."
2262667Sstever@eecs.umich.edu
2272667Sstever@eecs.umich.edu        bisect.insort_right(SimObject.modnames, self.modname)
2285742Snate@binkert.org
2295742Snate@binkert.orgclass SwigSource(SourceFile):
2305742Snate@binkert.org    '''Add a swig file to build'''
2312037SN/A
2322037SN/A    def __init__(self, package, source, **guards):
2332037SN/A        '''Specify the python package, the source file, and any guards'''
2345793Snate@binkert.org        super(SwigSource, self).__init__(source, skip_no_python=True, **guards)
2355793Snate@binkert.org
2365793Snate@binkert.org        modname,ext = self.extname
2375793Snate@binkert.org        assert ext == 'i'
2385793Snate@binkert.org
2394382Sbinkertn@umich.edu        self.module = modname
2404762Snate@binkert.org        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2415344Sstever@gmail.com        py_file = joinpath(self.dirname, modname + '.py')
2424382Sbinkertn@umich.edu
2435341Sstever@gmail.com        self.cc_source = Source(cc_file, swig=True, parent=self, **guards)
2445742Snate@binkert.org        self.py_source = PySource(package, py_file, parent=self, **guards)
2455742Snate@binkert.org
2465742Snate@binkert.orgclass ProtoBuf(SourceFile):
2475742Snate@binkert.org    '''Add a Protocol Buffer to build'''
2485742Snate@binkert.org
2494762Snate@binkert.org    def __init__(self, source, **guards):
2505742Snate@binkert.org        '''Specify the source file, and any guards'''
2515742Snate@binkert.org        super(ProtoBuf, self).__init__(source, **guards)
2525742Snate@binkert.org
2535742Snate@binkert.org        # Get the file name and the extension
2545742Snate@binkert.org        modname,ext = self.extname
2555742Snate@binkert.org        assert ext == 'proto'
2565742Snate@binkert.org
2575341Sstever@gmail.com        # Currently, we stick to generating the C++ headers, so we
2585742Snate@binkert.org        # only need to track the source and header.
2595341Sstever@gmail.com        self.cc_file = File(modname + '.pb.cc')
2604773Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
2616108Snate@binkert.org
2621858SN/Aclass UnitTest(object):
2631085SN/A    '''Create a UnitTest'''
2644382Sbinkertn@umich.edu
2654382Sbinkertn@umich.edu    all = []
2664762Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
2674762Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2684762Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2695517Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2705517Snate@binkert.org        target.'''
2715517Snate@binkert.org
2725517Snate@binkert.org        srcs = []
2735517Snate@binkert.org        for src in sources:
2745517Snate@binkert.org            if not isinstance(src, SourceFile):
2755517Snate@binkert.org                src = Source(src, skip_lib=True)
2765517Snate@binkert.org            src.guards[target] = True
2775517Snate@binkert.org            srcs.append(src)
2785517Snate@binkert.org
2795517Snate@binkert.org        self.sources = srcs
2805517Snate@binkert.org        self.target = target
2815517Snate@binkert.org        self.main = kwargs.get('main', False)
2825517Snate@binkert.org        UnitTest.all.append(self)
2835517Snate@binkert.org
2845517Snate@binkert.org# Children should have access
2855517Snate@binkert.orgExport('Source')
2865798Snate@binkert.orgExport('PySource')
2875517Snate@binkert.orgExport('SimObject')
2885517Snate@binkert.orgExport('SwigSource')
2895517Snate@binkert.orgExport('ProtoBuf')
2905517Snate@binkert.orgExport('UnitTest')
2915517Snate@binkert.org
2925517Snate@binkert.org########################################################################
2935517Snate@binkert.org#
2945517Snate@binkert.org# Debug Flags
2956143Snate@binkert.org#
2966143Snate@binkert.orgdebug_flags = {}
2975517Snate@binkert.orgdef DebugFlag(name, desc=None):
2985517Snate@binkert.org    if name in debug_flags:
2995517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3005517Snate@binkert.org    debug_flags[name] = (name, (), desc)
3015517Snate@binkert.org
3025517Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
3035517Snate@binkert.org    if name in debug_flags:
3045517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3055517Snate@binkert.org
3065517Snate@binkert.org    compound = tuple(flags)
3075517Snate@binkert.org    debug_flags[name] = (name, compound, desc)
3085517Snate@binkert.org
3095517Snate@binkert.orgExport('DebugFlag')
3105517Snate@binkert.orgExport('CompoundFlag')
3115798Snate@binkert.org
3125798Snate@binkert.org########################################################################
3135517Snate@binkert.org#
3145517Snate@binkert.org# Set some compiler variables
3156143Snate@binkert.org#
3166143Snate@binkert.org
3176143Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
3186143Snate@binkert.org# automatically expand '.' to refer to both the source directory and
3195517Snate@binkert.org# the corresponding build directory to pick up generated include
3206143Snate@binkert.org# files.
3215517Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
3225517Snate@binkert.org
3235517Snate@binkert.orgfor extra_dir in extras_dir_list:
3245517Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
3255517Snate@binkert.org
3265517Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3276143Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3286143Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3295517Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3304762Snate@binkert.org
3315517Snate@binkert.org########################################################################
3324762Snate@binkert.org#
3335517Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
3345517Snate@binkert.org#
3356143Snate@binkert.org
3366143Snate@binkert.orghere = Dir('.').srcnode().abspath
3375517Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3385517Snate@binkert.org    if root == here:
3395517Snate@binkert.org        # we don't want to recurse back into this SConscript
3405517Snate@binkert.org        continue
3415517Snate@binkert.org
3425517Snate@binkert.org    if 'SConscript' in files:
3435517Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3445517Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3455517Snate@binkert.org
3465517Snate@binkert.orgfor extra_dir in extras_dir_list:
3476143Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3485517Snate@binkert.org
3495517Snate@binkert.org    # Also add the corresponding build directory to pick up generated
3505517Snate@binkert.org    # include files.
3515517Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3525517Snate@binkert.org
3535517Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
3544762Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3554762Snate@binkert.org        if 'build' in dirs:
3564762Snate@binkert.org            dirs.remove('build')
3574762Snate@binkert.org
3584762Snate@binkert.org        if 'SConscript' in files:
3594762Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3606143Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3614762Snate@binkert.org
3624762Snate@binkert.orgfor opt in export_vars:
3634762Snate@binkert.org    env.ConfigFile(opt)
3644762Snate@binkert.org
3654382Sbinkertn@umich.edudef makeTheISA(source, target, env):
3664382Sbinkertn@umich.edu    isas = [ src.get_contents() for src in source ]
3675517Snate@binkert.org    target_isa = env['TARGET_ISA']
3685517Snate@binkert.org    def define(isa):
3695517Snate@binkert.org        return isa.upper() + '_ISA'
3705517Snate@binkert.org    
3715798Snate@binkert.org    def namespace(isa):
3725798Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA' 
3735824Ssaidi@eecs.umich.edu
3745517Snate@binkert.org
3755517Snate@binkert.org    code = code_formatter()
3765863Snate@binkert.org    code('''\
3775798Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3785798Snate@binkert.org#define __CONFIG_THE_ISA_HH__
3795798Snate@binkert.org
3805798Snate@binkert.org''')
3815517Snate@binkert.org
3825517Snate@binkert.org    # create defines for the preprocessing and compile-time determination
3835517Snate@binkert.org    for i,isa in enumerate(isas):
3845517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
3855517Snate@binkert.org    code()
3865517Snate@binkert.org
3875517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
3885517Snate@binkert.org    # reuse the same name as the namespaces
3895798Snate@binkert.org    code('enum class Arch {')
3905798Snate@binkert.org    for i,isa in enumerate(isas):
3915798Snate@binkert.org        if i + 1 == len(isas):
3925798Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
3935798Snate@binkert.org        else:
3945798Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
3955517Snate@binkert.org    code('};')
3965517Snate@binkert.org
3975517Snate@binkert.org    code('''
3985517Snate@binkert.org
3995517Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
4005517Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
4015517Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
4025517Snate@binkert.org
4035517Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
4044762Snate@binkert.org
4054382Sbinkertn@umich.edu    code.write(str(target[0]))
4066143Snate@binkert.org
4075517Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4084382Sbinkertn@umich.edu            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4094382Sbinkertn@umich.edu
4104762Snate@binkert.org########################################################################
4114762Snate@binkert.org#
4124762Snate@binkert.org# Prevent any SimObjects from being added after this point, they
4134762Snate@binkert.org# should all have been added in the SConscripts above
4144762Snate@binkert.org#
4155517Snate@binkert.orgSimObject.fixed = True
4165517Snate@binkert.org
4175517Snate@binkert.orgclass DictImporter(object):
4185517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4195517Snate@binkert.org    map to arbitrary filenames.'''
4205517Snate@binkert.org    def __init__(self, modules):
4215517Snate@binkert.org        self.modules = modules
4225517Snate@binkert.org        self.installed = set()
4236143Snate@binkert.org
4245517Snate@binkert.org    def __del__(self):
4255517Snate@binkert.org        self.unload()
4265517Snate@binkert.org
4275517Snate@binkert.org    def unload(self):
4285517Snate@binkert.org        import sys
4295517Snate@binkert.org        for module in self.installed:
4305517Snate@binkert.org            del sys.modules[module]
4315517Snate@binkert.org        self.installed = set()
4325517Snate@binkert.org
4335517Snate@binkert.org    def find_module(self, fullname, path):
4346143Snate@binkert.org        if fullname == 'm5.defines':
4355517Snate@binkert.org            return self
4365517Snate@binkert.org
4375517Snate@binkert.org        if fullname == 'm5.objects':
4385517Snate@binkert.org            return self
4395517Snate@binkert.org
4405517Snate@binkert.org        if fullname.startswith('m5.internal'):
4415517Snate@binkert.org            return None
4425517Snate@binkert.org
4435517Snate@binkert.org        source = self.modules.get(fullname, None)
4445517Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
4455517Snate@binkert.org            return self
4465517Snate@binkert.org
4475517Snate@binkert.org        return None
4485517Snate@binkert.org
4495517Snate@binkert.org    def load_module(self, fullname):
4505517Snate@binkert.org        mod = imp.new_module(fullname)
4515517Snate@binkert.org        sys.modules[fullname] = mod
4525517Snate@binkert.org        self.installed.add(fullname)
4535517Snate@binkert.org
4546143Snate@binkert.org        mod.__loader__ = self
4555517Snate@binkert.org        if fullname == 'm5.objects':
4564762Snate@binkert.org            mod.__path__ = fullname.split('.')
4574762Snate@binkert.org            return mod
4586143Snate@binkert.org
4596143Snate@binkert.org        if fullname == 'm5.defines':
4606143Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
4614762Snate@binkert.org            return mod
4624762Snate@binkert.org
4634762Snate@binkert.org        source = self.modules[fullname]
4645517Snate@binkert.org        if source.modname == '__init__':
4654762Snate@binkert.org            mod.__path__ = source.modpath
4664762Snate@binkert.org        mod.__file__ = source.abspath
4674762Snate@binkert.org
4685463Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
4695517Snate@binkert.org
4704762Snate@binkert.org        return mod
4714762Snate@binkert.org
4724762Snate@binkert.orgimport m5.SimObject
4734762Snate@binkert.orgimport m5.params
4744762Snate@binkert.orgfrom m5.util import code_formatter
4754762Snate@binkert.org
4765463Snate@binkert.orgm5.SimObject.clear()
4775517Snate@binkert.orgm5.params.clear()
4784762Snate@binkert.org
4794762Snate@binkert.org# install the python importer so we can grab stuff from the source
4804762Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
4816143Snate@binkert.org# else we won't know about them for the rest of the stuff.
4826143Snate@binkert.orgimporter = DictImporter(PySource.modules)
4836143Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
4844762Snate@binkert.org
4854762Snate@binkert.org# import all sim objects so we can populate the all_objects list
4865517Snate@binkert.org# make sure that we're working with a list, then let's sort it
4874762Snate@binkert.orgfor modname in SimObject.modnames:
4884762Snate@binkert.org    exec('from m5.objects import %s' % modname)
4894762Snate@binkert.org
4904762Snate@binkert.org# we need to unload all of the currently imported modules so that they
4915517Snate@binkert.org# will be re-imported the next time the sconscript is run
4924762Snate@binkert.orgimporter.unload()
4934762Snate@binkert.orgsys.meta_path.remove(importer)
4944762Snate@binkert.org
4954762Snate@binkert.orgsim_objects = m5.SimObject.allClasses
4965517Snate@binkert.orgall_enums = m5.params.allEnums
4975517Snate@binkert.org
4985517Snate@binkert.orgif m5.SimObject.noCxxHeader:
4995517Snate@binkert.org    print >> sys.stderr, \
5005517Snate@binkert.org        "warning: At least one SimObject lacks a header specification. " \
5015517Snate@binkert.org        "This can cause unexpected results in the generated SWIG " \
5025517Snate@binkert.org        "wrappers."
5035517Snate@binkert.org
5045517Snate@binkert.org# Find param types that need to be explicitly wrapped with swig.
5055517Snate@binkert.org# These will be recognized because the ParamDesc will have a
5065517Snate@binkert.org# swig_decl() method.  Most param types are based on types that don't
5075517Snate@binkert.org# need this, either because they're based on native types (like Int)
5085517Snate@binkert.org# or because they're SimObjects (which get swigged independently).
5095517Snate@binkert.org# For now the only things handled here are VectorParam types.
5105517Snate@binkert.orgparams_to_swig = {}
5115517Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
5125517Snate@binkert.org    for param in obj._params.local.values():
5135517Snate@binkert.org        # load the ptype attribute now because it depends on the
5145517Snate@binkert.org        # current version of SimObject.allClasses, but when scons
5155517Snate@binkert.org        # actually uses the value, all versions of
5165517Snate@binkert.org        # SimObject.allClasses will have been loaded
5175517Snate@binkert.org        param.ptype
5185517Snate@binkert.org
5195517Snate@binkert.org        if not hasattr(param, 'swig_decl'):
5205517Snate@binkert.org            continue
5215517Snate@binkert.org        pname = param.ptype_str
5225517Snate@binkert.org        if pname not in params_to_swig:
5235517Snate@binkert.org            params_to_swig[pname] = param
5245517Snate@binkert.org
5255517Snate@binkert.org########################################################################
5265517Snate@binkert.org#
5275517Snate@binkert.org# calculate extra dependencies
5285517Snate@binkert.org#
5295517Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5305517Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
5315517Snate@binkert.orgdepends.sort(key = lambda x: x.name)
5325517Snate@binkert.org
5335517Snate@binkert.org########################################################################
5345517Snate@binkert.org#
5355517Snate@binkert.org# Commands for the basic automatically generated python files
5365517Snate@binkert.org#
5375517Snate@binkert.org
5385517Snate@binkert.org# Generate Python file containing a dict specifying the current
5395517Snate@binkert.org# buildEnv flags.
5405517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
5415517Snate@binkert.org    build_env = source[0].get_contents()
5425517Snate@binkert.org
5435517Snate@binkert.org    code = code_formatter()
5445517Snate@binkert.org    code("""
5455517Snate@binkert.orgimport m5.internal
5465517Snate@binkert.orgimport m5.util
5475517Snate@binkert.org
5485517Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
5495517Snate@binkert.org
5505517Snate@binkert.orgcompileDate = m5.internal.core.compileDate
5515517Snate@binkert.org_globals = globals()
5525517Snate@binkert.orgfor key,val in m5.internal.core.__dict__.iteritems():
5535517Snate@binkert.org    if key.startswith('flag_'):
5545517Snate@binkert.org        flag = key[5:]
5555517Snate@binkert.org        _globals[flag] = val
5565517Snate@binkert.orgdel _globals
5575517Snate@binkert.org""")
5585517Snate@binkert.org    code.write(target[0].abspath)
5595517Snate@binkert.org
5605517Snate@binkert.orgdefines_info = Value(build_env)
5615517Snate@binkert.org# Generate a file with all of the compile options in it
5625610Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
5635623Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
5645623Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
5655623Snate@binkert.org
5665610Snate@binkert.org# Generate python file containing info about the M5 source code
5675517Snate@binkert.orgdef makeInfoPyFile(target, source, env):
5685623Snate@binkert.org    code = code_formatter()
5695623Snate@binkert.org    for src in source:
5705623Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
5715623Snate@binkert.org        code('$src = ${{repr(data)}}')
5725623Snate@binkert.org    code.write(str(target[0]))
5735623Snate@binkert.org
5745623Snate@binkert.org# Generate a file that wraps the basic top level files
5755517Snate@binkert.orgenv.Command('python/m5/info.py',
5765610Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
5775610Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
5785610Snate@binkert.orgPySource('m5', 'python/m5/info.py')
5795610Snate@binkert.org
5805517Snate@binkert.org########################################################################
5815517Snate@binkert.org#
5825610Snate@binkert.org# Create all of the SimObject param headers and enum headers
5835610Snate@binkert.org#
5845517Snate@binkert.org
5855517Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
5865517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5875517Snate@binkert.org
5885517Snate@binkert.org    name = str(source[0].get_contents())
5895517Snate@binkert.org    obj = sim_objects[name]
5905517Snate@binkert.org
5915517Snate@binkert.org    code = code_formatter()
5925517Snate@binkert.org    obj.cxx_param_decl(code)
5935517Snate@binkert.org    code.write(target[0].abspath)
5944762Snate@binkert.org
5956143Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
5966143Snate@binkert.org    def body(target, source, env):
5975463Snate@binkert.org        assert len(target) == 1 and len(source) == 1
5984762Snate@binkert.org
5994762Snate@binkert.org        name = str(source[0].get_contents())
6004762Snate@binkert.org        obj = sim_objects[name]
6016143Snate@binkert.org
6026143Snate@binkert.org        code = code_formatter()
6034382Sbinkertn@umich.edu        obj.cxx_config_param_file(code, is_header)
6044382Sbinkertn@umich.edu        code.write(target[0].abspath)
6056143Snate@binkert.org    return body
6066143Snate@binkert.org
6074382Sbinkertn@umich.edudef createParamSwigWrapper(target, source, env):
6084762Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6095517Snate@binkert.org
6105517Snate@binkert.org    name = str(source[0].get_contents())
6115517Snate@binkert.org    param = params_to_swig[name]
6125517Snate@binkert.org
6135517Snate@binkert.org    code = code_formatter()
6145517Snate@binkert.org    param.swig_decl(code)
6155522Snate@binkert.org    code.write(target[0].abspath)
6165517Snate@binkert.org
6175517Snate@binkert.orgdef createEnumStrings(target, source, env):
6185517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6195517Snate@binkert.org
6205517Snate@binkert.org    name = str(source[0].get_contents())
6216143Snate@binkert.org    obj = all_enums[name]
6226143Snate@binkert.org
6236143Snate@binkert.org    code = code_formatter()
6245522Snate@binkert.org    obj.cxx_def(code)
6254382Sbinkertn@umich.edu    code.write(target[0].abspath)
6266229Snate@binkert.org
6276229Snate@binkert.orgdef createEnumDecls(target, source, env):
6286229Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6296229Snate@binkert.org
6306229Snate@binkert.org    name = str(source[0].get_contents())
6316229Snate@binkert.org    obj = all_enums[name]
6326229Snate@binkert.org
6336229Snate@binkert.org    code = code_formatter()
6346229Snate@binkert.org    obj.cxx_decl(code)
6356229Snate@binkert.org    code.write(target[0].abspath)
6366229Snate@binkert.org
6376229Snate@binkert.orgdef createEnumSwigWrapper(target, source, env):
6386229Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6396229Snate@binkert.org
6406229Snate@binkert.org    name = str(source[0].get_contents())
6416229Snate@binkert.org    obj = all_enums[name]
6426229Snate@binkert.org
6436229Snate@binkert.org    code = code_formatter()
6446229Snate@binkert.org    obj.swig_decl(code)
6456229Snate@binkert.org    code.write(target[0].abspath)
6466229Snate@binkert.org
6475192Ssaidi@eecs.umich.edudef createSimObjectSwigWrapper(target, source, env):
6485517Snate@binkert.org    name = source[0].get_contents()
6495517Snate@binkert.org    obj = sim_objects[name]
6505517Snate@binkert.org
6515517Snate@binkert.org    code = code_formatter()
6526229Snate@binkert.org    obj.swig_decl(code)
6536229Snate@binkert.org    code.write(target[0].abspath)
6545799Snate@binkert.org
6555799Snate@binkert.org# dummy target for generated code
6565517Snate@binkert.org# we start out with all the Source files so they get copied to build/*/ also.
6575517Snate@binkert.orgSWIG = env.Dummy('swig', [s.tnode for s in Source.get()])
6585517Snate@binkert.org
6595517Snate@binkert.org# Generate all of the SimObject param C++ struct header files
6605517Snate@binkert.orgparams_hh_files = []
6615517Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
6625799Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6635517Snate@binkert.org    extra_deps = [ py_source.tnode ]
6645517Snate@binkert.org
6655517Snate@binkert.org    hh_file = File('params/%s.hh' % name)
6665517Snate@binkert.org    params_hh_files.append(hh_file)
6675517Snate@binkert.org    env.Command(hh_file, Value(name),
6685517Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6695517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
6705799Snate@binkert.org    env.Depends(SWIG, hh_file)
6715517Snate@binkert.org
6725517Snate@binkert.org# C++ parameter description files
6735799Snate@binkert.orgif GetOption('with_cxx_config'):
6745517Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
6755517Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
6765517Snate@binkert.org        extra_deps = [ py_source.tnode ]
6775517Snate@binkert.org
6785517Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
6795517Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
6805517Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
6815517Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
6825799Snate@binkert.org                    Transform("CXXCPRHH")))
6835517Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
6845517Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
6855517Snate@binkert.org                    Transform("CXXCPRCC")))
6865517Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
6875517Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
6885517Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
6895517Snate@binkert.org                    [cxx_config_hh_file])
6905517Snate@binkert.org        Source(cxx_config_cc_file)
6915517Snate@binkert.org
6925517Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
6935517Snate@binkert.org
6945517Snate@binkert.org    def createCxxConfigInitCC(target, source, env):
6956229Snate@binkert.org        assert len(target) == 1 and len(source) == 1
6965517Snate@binkert.org
6975517Snate@binkert.org        code = code_formatter()
6985517Snate@binkert.org
6995517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7005517Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
7015517Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
7025517Snate@binkert.org        code()
7035517Snate@binkert.org        code('void cxxConfigInit()')
7045517Snate@binkert.org        code('{')
7055517Snate@binkert.org        code.indent()
7065517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7075517Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
7085517Snate@binkert.org                not simobj.abstract
7095517Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
7105517Snate@binkert.org                code('cxx_config_directory["${name}"] = '
7115517Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
7125517Snate@binkert.org        code.dedent()
7135517Snate@binkert.org        code('}')
7145517Snate@binkert.org        code.write(target[0].abspath)
7155517Snate@binkert.org
7165517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
7175517Snate@binkert.org    extra_deps = [ py_source.tnode ]
7185517Snate@binkert.org    env.Command(cxx_config_init_cc_file, Value(name),
7195517Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
7205517Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
7215517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
7225517Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
7235517Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
7245517Snate@binkert.org            [File('sim/cxx_config.hh')])
7255517Snate@binkert.org    Source(cxx_config_init_cc_file)
7265517Snate@binkert.org
7275517Snate@binkert.org# Generate any needed param SWIG wrapper files
7285517Snate@binkert.orgparams_i_files = []
7295517Snate@binkert.orgfor name,param in sorted(params_to_swig.iteritems()):
7305517Snate@binkert.org    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
7315517Snate@binkert.org    params_i_files.append(i_file)
7325517Snate@binkert.org    env.Command(i_file, Value(name),
7335517Snate@binkert.org                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
7345517Snate@binkert.org    env.Depends(i_file, depends)
7355517Snate@binkert.org    env.Depends(SWIG, i_file)
7365517Snate@binkert.org    SwigSource('m5.internal', i_file)
7375517Snate@binkert.org
7385517Snate@binkert.org# Generate all enum header files
7395517Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
7405517Snate@binkert.org    py_source = PySource.modules[enum.__module__]
7415517Snate@binkert.org    extra_deps = [ py_source.tnode ]
7425517Snate@binkert.org
7435517Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
7445517Snate@binkert.org    env.Command(cc_file, Value(name),
7455517Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
7465517Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
7475517Snate@binkert.org    env.Depends(SWIG, cc_file)
7485517Snate@binkert.org    Source(cc_file)
7495517Snate@binkert.org
7505517Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
7515517Snate@binkert.org    env.Command(hh_file, Value(name),
7525517Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
7535517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
7545517Snate@binkert.org    env.Depends(SWIG, hh_file)
7555517Snate@binkert.org
7565517Snate@binkert.org    i_file = File('python/m5/internal/enum_%s.i' % name)
7575517Snate@binkert.org    env.Command(i_file, Value(name),
7585517Snate@binkert.org                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
7595517Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
7605517Snate@binkert.org    env.Depends(SWIG, i_file)
7615517Snate@binkert.org    SwigSource('m5.internal', i_file)
7625517Snate@binkert.org
7635517Snate@binkert.org# Generate SimObject SWIG wrapper files
7645517Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
7655517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
7665517Snate@binkert.org    extra_deps = [ py_source.tnode ]
7675517Snate@binkert.org    i_file = File('python/m5/internal/param_%s.i' % name)
7686229Snate@binkert.org    env.Command(i_file, Value(name),
7695517Snate@binkert.org                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
7705517Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
7715517Snate@binkert.org    SwigSource('m5.internal', i_file)
7725517Snate@binkert.org
7735517Snate@binkert.org# Generate the main swig init file
7745517Snate@binkert.orgdef makeEmbeddedSwigInit(target, source, env):
7755517Snate@binkert.org    code = code_formatter()
7765517Snate@binkert.org    module = source[0].get_contents()
7775517Snate@binkert.org    code('''\
7785517Snate@binkert.org#include "sim/init.hh"
7795517Snate@binkert.org
7805517Snate@binkert.orgextern "C" {
7815517Snate@binkert.org    void init_${module}();
7825517Snate@binkert.org}
7835517Snate@binkert.org
7845517Snate@binkert.orgEmbeddedSwig embed_swig_${module}(init_${module});
7855517Snate@binkert.org''')
7865517Snate@binkert.org    code.write(str(target[0]))
7875517Snate@binkert.org    
7885517Snate@binkert.org# Build all swig modules
7895517Snate@binkert.orgfor swig in SwigSource.all:
7905517Snate@binkert.org    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
7915517Snate@binkert.org                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
7925517Snate@binkert.org                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
7935517Snate@binkert.org    cc_file = str(swig.tnode)
7945517Snate@binkert.org    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
7955517Snate@binkert.org    env.Command(init_file, Value(swig.module),
7965517Snate@binkert.org                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
7975517Snate@binkert.org    env.Depends(SWIG, init_file)
7985517Snate@binkert.org    Source(init_file, **swig.guards)
7995517Snate@binkert.org
8005517Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
8015517Snate@binkert.orgif env['HAVE_PROTOBUF']:
8025517Snate@binkert.org    for proto in ProtoBuf.all:
8035517Snate@binkert.org        # Use both the source and header as the target, and the .proto
8045517Snate@binkert.org        # file as the source. When executing the protoc compiler, also
8055517Snate@binkert.org        # specify the proto_path to avoid having the generated files
8065517Snate@binkert.org        # include the path.
8075517Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
8085517Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
8095517Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
8105517Snate@binkert.org                               Transform("PROTOC")))
8115517Snate@binkert.org
8125517Snate@binkert.org        env.Depends(SWIG, [proto.cc_file, proto.hh_file])
8135517Snate@binkert.org        # Add the C++ source file
8145517Snate@binkert.org        Source(proto.cc_file, **proto.guards)
8155517Snate@binkert.orgelif ProtoBuf.all:
8165517Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
8175517Snate@binkert.org    Exit(1)
8185517Snate@binkert.org
8195517Snate@binkert.org#
8205517Snate@binkert.org# Handle debug flags
8215517Snate@binkert.org#
8225517Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
8235517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8245517Snate@binkert.org
8255517Snate@binkert.org    code = code_formatter()
8265517Snate@binkert.org
8275517Snate@binkert.org    # delay definition of CompoundFlags until after all the definition
8285517Snate@binkert.org    # of all constituent SimpleFlags
8295517Snate@binkert.org    comp_code = code_formatter()
8306143Snate@binkert.org
8315517Snate@binkert.org    # file header
8325192Ssaidi@eecs.umich.edu    code('''
8335192Ssaidi@eecs.umich.edu/*
8345517Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8355517Snate@binkert.org */
8365192Ssaidi@eecs.umich.edu
8375192Ssaidi@eecs.umich.edu#include "base/debug.hh"
8385522Snate@binkert.org
8395522Snate@binkert.orgnamespace Debug {
8405522Snate@binkert.org
8415522Snate@binkert.org''')
8425522Snate@binkert.org
8435522Snate@binkert.org    for name, flag in sorted(source[0].read().iteritems()):
8445522Snate@binkert.org        n, compound, desc = flag
8455522Snate@binkert.org        assert n == name
8465522Snate@binkert.org
8475522Snate@binkert.org        if not compound:
8485517Snate@binkert.org            code('SimpleFlag $name("$name", "$desc");')
8495522Snate@binkert.org        else:
8505522Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
8515517Snate@binkert.org            comp_code.indent()
8526143Snate@binkert.org            last = len(compound) - 1
8535604Snate@binkert.org            for i,flag in enumerate(compound):
8545522Snate@binkert.org                if i != last:
8555522Snate@binkert.org                    comp_code('&$flag,')
8565522Snate@binkert.org                else:
8575517Snate@binkert.org                    comp_code('&$flag);')
8585522Snate@binkert.org            comp_code.dedent()
8595522Snate@binkert.org
8605522Snate@binkert.org    code.append(comp_code)
8615522Snate@binkert.org    code()
8625522Snate@binkert.org    code('} // namespace Debug')
8635522Snate@binkert.org
8645522Snate@binkert.org    code.write(str(target[0]))
8655522Snate@binkert.org
8665522Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
8675522Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8685522Snate@binkert.org
8695522Snate@binkert.org    val = eval(source[0].get_contents())
8705522Snate@binkert.org    name, compound, desc = val
8715522Snate@binkert.org
8725522Snate@binkert.org    code = code_formatter()
8735522Snate@binkert.org
8745522Snate@binkert.org    # file header boilerplate
8755522Snate@binkert.org    code('''\
8765522Snate@binkert.org/*
8776143Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8785522Snate@binkert.org */
8795522Snate@binkert.org
8804382Sbinkertn@umich.edu#ifndef __DEBUG_${name}_HH__
8815522Snate@binkert.org#define __DEBUG_${name}_HH__
8825522Snate@binkert.org
8835522Snate@binkert.orgnamespace Debug {
8845522Snate@binkert.org''')
8855522Snate@binkert.org
8865522Snate@binkert.org    if compound:
8875522Snate@binkert.org        code('class CompoundFlag;')
8884382Sbinkertn@umich.edu    code('class SimpleFlag;')
8895522Snate@binkert.org
8906143Snate@binkert.org    if compound:
8915522Snate@binkert.org        code('extern CompoundFlag $name;')
8925522Snate@binkert.org        for flag in compound:
8935522Snate@binkert.org            code('extern SimpleFlag $flag;')
8945522Snate@binkert.org    else:
8955522Snate@binkert.org        code('extern SimpleFlag $name;')
8965522Snate@binkert.org
8975522Snate@binkert.org    code('''
8985522Snate@binkert.org}
8995522Snate@binkert.org
9005522Snate@binkert.org#endif // __DEBUG_${name}_HH__
9015522Snate@binkert.org''')
9025522Snate@binkert.org
9035522Snate@binkert.org    code.write(str(target[0]))
9045522Snate@binkert.org
9055522Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
9065522Snate@binkert.org    n, compound, desc = flag
9075522Snate@binkert.org    assert n == name
9085522Snate@binkert.org
9095522Snate@binkert.org    hh_file = 'debug/%s.hh' % name
9105522Snate@binkert.org    env.Command(hh_file, Value(flag),
9115522Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
9125522Snate@binkert.org    env.Depends(SWIG, hh_file)
9135522Snate@binkert.org
9145522Snate@binkert.orgenv.Command('debug/flags.cc', Value(debug_flags),
9155522Snate@binkert.org            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
9165522Snate@binkert.orgenv.Depends(SWIG, 'debug/flags.cc')
9176143Snate@binkert.orgSource('debug/flags.cc')
9186143Snate@binkert.org
9196143Snate@binkert.org# version tags
9206143Snate@binkert.orgenv.Command('sim/tags.cc', None,
9215522Snate@binkert.org            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
9224382Sbinkertn@umich.edu                       Transform("VER TAGS")))
9234382Sbinkertn@umich.edu
9244382Sbinkertn@umich.edu# Embed python files.  All .py files that have been indicated by a
9254382Sbinkertn@umich.edu# PySource() call in a SConscript need to be embedded into the M5
9264382Sbinkertn@umich.edu# library.  To do that, we compile the file to byte code, marshal the
9274382Sbinkertn@umich.edu# byte code, compress it, and then generate a c++ file that
9284382Sbinkertn@umich.edu# inserts the result into an array.
9294382Sbinkertn@umich.edudef embedPyFile(target, source, env):
9304382Sbinkertn@umich.edu    def c_str(string):
9314382Sbinkertn@umich.edu        if string is None:
9326143Snate@binkert.org            return "0"
933955SN/A        return '"%s"' % string
9342655Sstever@eecs.umich.edu
9352655Sstever@eecs.umich.edu    '''Action function to compile a .py into a code object, marshal
9362655Sstever@eecs.umich.edu    it, compress it, and stick it into an asm file so the code appears
9372655Sstever@eecs.umich.edu    as just bytes with a label in the data section'''
9382655Sstever@eecs.umich.edu
9395601Snate@binkert.org    src = file(str(source[0]), 'r').read()
9405601Snate@binkert.org
9415601Snate@binkert.org    pysource = PySource.tnodes[source[0]]
9425601Snate@binkert.org    compiled = compile(src, pysource.abspath, 'exec')
9435522Snate@binkert.org    marshalled = marshal.dumps(compiled)
9445863Snate@binkert.org    compressed = zlib.compress(marshalled)
9455601Snate@binkert.org    data = compressed
9465601Snate@binkert.org    sym = pysource.symname
9475601Snate@binkert.org
9485863Snate@binkert.org    code = code_formatter()
9496143Snate@binkert.org    code('''\
9505559Snate@binkert.org#include "sim/init.hh"
9515559Snate@binkert.org
9525559Snate@binkert.orgnamespace {
9535559Snate@binkert.org
9545601Snate@binkert.orgconst uint8_t data_${sym}[] = {
9556143Snate@binkert.org''')
9566143Snate@binkert.org    code.indent()
9576143Snate@binkert.org    step = 16
9586143Snate@binkert.org    for i in xrange(0, len(data), step):
9596143Snate@binkert.org        x = array.array('B', data[i:i+step])
9606143Snate@binkert.org        code(''.join('%d,' % d for d in x))
9616143Snate@binkert.org    code.dedent()
9626143Snate@binkert.org    
9636143Snate@binkert.org    code('''};
9646143Snate@binkert.org
9656143Snate@binkert.orgEmbeddedPython embedded_${sym}(
9666143Snate@binkert.org    ${{c_str(pysource.arcname)}},
9676143Snate@binkert.org    ${{c_str(pysource.abspath)}},
9686143Snate@binkert.org    ${{c_str(pysource.modpath)}},
9696143Snate@binkert.org    data_${sym},
9706143Snate@binkert.org    ${{len(data)}},
9716143Snate@binkert.org    ${{len(marshalled)}});
9726143Snate@binkert.org
9736143Snate@binkert.org} // anonymous namespace
9746143Snate@binkert.org''')
9756143Snate@binkert.org    code.write(str(target[0]))
9766143Snate@binkert.org
9776143Snate@binkert.orgfor source in PySource.all:
9786143Snate@binkert.org    env.Command(source.cpp, source.tnode,
9796143Snate@binkert.org                MakeAction(embedPyFile, Transform("EMBED PY")))
9806143Snate@binkert.org    env.Depends(SWIG, source.cpp)
9816143Snate@binkert.org    Source(source.cpp, skip_no_python=True)
9826143Snate@binkert.org
9836143Snate@binkert.org########################################################################
9846143Snate@binkert.org#
9856143Snate@binkert.org# Define binaries.  Each different build type (debug, opt, etc.) gets
9866143Snate@binkert.org# a slightly different build environment.
9876240Snate@binkert.org#
9885554Snate@binkert.org
9895522Snate@binkert.org# List of constructed environments to pass back to SConstruct
9905522Snate@binkert.orgdate_source = Source('base/date.cc', skip_lib=True)
9915797Snate@binkert.org
9925797Snate@binkert.org# Capture this directory for the closure makeEnv, otherwise when it is
9935522Snate@binkert.org# called, it won't know what directory it should use.
9945584Snate@binkert.orgvariant_dir = Dir('.').path
9956143Snate@binkert.orgdef variant(*path):
9965862Snate@binkert.org    return os.path.join(variant_dir, *path)
9975584Snate@binkert.orgdef variantd(*path):
9985601Snate@binkert.org    return variant(*path)+'/'
9996143Snate@binkert.org
10006143Snate@binkert.org# Function to create a new build environment as clone of current
10012655Sstever@eecs.umich.edu# environment 'env' with modified object suffix and optional stripped
10026143Snate@binkert.org# binary.  Additional keyword arguments are appended to corresponding
10036143Snate@binkert.org# build environment vars.
10046143Snate@binkert.orgdef makeEnv(env, label, objsfx, strip = False, **kwargs):
10056143Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
10066143Snate@binkert.org    # name.  Use '_' instead.
10074007Ssaidi@eecs.umich.edu    libname = variant('gem5_' + label)
10084596Sbinkertn@umich.edu    exename = variant('gem5.' + label)
10094007Ssaidi@eecs.umich.edu    secondary_exename = variant('m5.' + label)
10104596Sbinkertn@umich.edu
10116143Snate@binkert.org    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
10125522Snate@binkert.org    new_env.Label = label
10135601Snate@binkert.org    new_env.Append(**kwargs)
10145601Snate@binkert.org
10152655Sstever@eecs.umich.edu    swig_env = new_env.Clone()
1016955SN/A
10173918Ssaidi@eecs.umich.edu    # Both gcc and clang have issues with unused labels and values in
10183918Ssaidi@eecs.umich.edu    # the SWIG generated code
10193918Ssaidi@eecs.umich.edu    swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
10203918Ssaidi@eecs.umich.edu
10213918Ssaidi@eecs.umich.edu    if env['GCC']:
10223918Ssaidi@eecs.umich.edu        # Depending on the SWIG version, we also need to supress
10233918Ssaidi@eecs.umich.edu        # warnings about uninitialized variables and missing field
10243918Ssaidi@eecs.umich.edu        # initializers.
10253918Ssaidi@eecs.umich.edu        swig_env.Append(CCFLAGS=['-Wno-uninitialized',
10263918Ssaidi@eecs.umich.edu                                 '-Wno-missing-field-initializers',
10273918Ssaidi@eecs.umich.edu                                 '-Wno-unused-but-set-variable',
10283918Ssaidi@eecs.umich.edu                                 '-Wno-maybe-uninitialized',
10293918Ssaidi@eecs.umich.edu                                 '-Wno-type-limits'])
10303918Ssaidi@eecs.umich.edu
10313940Ssaidi@eecs.umich.edu        # Only gcc >= 4.9 supports UBSan, so check both the version
10323940Ssaidi@eecs.umich.edu        # and the command-line option before adding the compiler and
10333940Ssaidi@eecs.umich.edu        # linker flags.
10343942Ssaidi@eecs.umich.edu        if GetOption('with_ubsan') and \
10353940Ssaidi@eecs.umich.edu                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
10363515Ssaidi@eecs.umich.edu            new_env.Append(CCFLAGS='-fsanitize=undefined')
10373918Ssaidi@eecs.umich.edu            new_env.Append(LINKFLAGS='-fsanitize=undefined')
10384762Snate@binkert.org
10393515Ssaidi@eecs.umich.edu    if env['CLANG']:
10402655Sstever@eecs.umich.edu        swig_env.Append(CCFLAGS=['-Wno-sometimes-uninitialized',
10413918Ssaidi@eecs.umich.edu                                 '-Wno-deprecated-register',
10423619Sbinkertn@umich.edu                                 '-Wno-tautological-compare'])
1043955SN/A
1044955SN/A        # All supported clang versions have support for UBSan, so if
10452655Sstever@eecs.umich.edu        # asked to use it, append the compiler and linker flags.
10463918Ssaidi@eecs.umich.edu        if GetOption('with_ubsan'):
10473619Sbinkertn@umich.edu            new_env.Append(CCFLAGS='-fsanitize=undefined')
1048955SN/A            new_env.Append(LINKFLAGS='-fsanitize=undefined')
1049955SN/A
10502655Sstever@eecs.umich.edu    werror_env = new_env.Clone()
10513918Ssaidi@eecs.umich.edu    # Treat warnings as errors but white list some warnings that we
10523619Sbinkertn@umich.edu    # want to allow (e.g., deprecation warnings).
1053955SN/A    werror_env.Append(CCFLAGS=['-Werror',
1054955SN/A                               '-Wno-error=deprecated-declarations',
10552655Sstever@eecs.umich.edu                               '-Wno-error=deprecated',
10563918Ssaidi@eecs.umich.edu                               ])
10573683Sstever@eecs.umich.edu
10582655Sstever@eecs.umich.edu    def make_obj(source, static, extra_deps = None):
10591869SN/A        '''This function adds the specified source to the correct
10601869SN/A        build environment, and returns the corresponding SCons Object
1061        nodes'''
1062
1063        if source.swig:
1064            env = swig_env
1065        elif source.Werror:
1066            env = werror_env
1067        else:
1068            env = new_env
1069
1070        if static:
1071            obj = env.StaticObject(source.tnode)
1072        else:
1073            obj = env.SharedObject(source.tnode)
1074
1075        if extra_deps:
1076            env.Depends(obj, extra_deps)
1077
1078        return obj
1079
1080    lib_guards = {'main': False, 'skip_lib': False}
1081
1082    # Without Python, leave out all SWIG and Python content from the
1083    # library builds.  The option doesn't affect gem5 built as a program
1084    if GetOption('without_python'):
1085        lib_guards['skip_no_python'] = False
1086
1087    static_objs = [ make_obj(s, True) for s in Source.get(**lib_guards) ]
1088    shared_objs = [ make_obj(s, False) for s in Source.get(**lib_guards) ]
1089
1090    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
1091    static_objs.append(static_date)
1092
1093    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
1094    shared_objs.append(shared_date)
1095
1096    # First make a library of everything but main() so other programs can
1097    # link against m5.
1098    static_lib = new_env.StaticLibrary(libname, static_objs)
1099    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1100
1101    # Now link a stub with main() and the static library.
1102    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
1103
1104    for test in UnitTest.all:
1105        flags = { test.target : True }
1106        test_sources = Source.get(**flags)
1107        test_objs = [ make_obj(s, static=True) for s in test_sources ]
1108        if test.main:
1109            test_objs += main_objs
1110        path = variant('unittest/%s.%s' % (test.target, label))
1111        new_env.Program(path, test_objs + static_objs)
1112
1113    progname = exename
1114    if strip:
1115        progname += '.unstripped'
1116
1117    targets = new_env.Program(progname, main_objs + static_objs)
1118
1119    if strip:
1120        if sys.platform == 'sunos5':
1121            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1122        else:
1123            cmd = 'strip $SOURCE -o $TARGET'
1124        targets = new_env.Command(exename, progname,
1125                    MakeAction(cmd, Transform("STRIP")))
1126
1127    new_env.Command(secondary_exename, exename,
1128            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1129
1130    new_env.M5Binary = targets[0]
1131    return new_env
1132
1133# Start out with the compiler flags common to all compilers,
1134# i.e. they all use -g for opt and -g -pg for prof
1135ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1136           'perf' : ['-g']}
1137
1138# Start out with the linker flags common to all linkers, i.e. -pg for
1139# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1140# no-as-needed and as-needed as the binutils linker is too clever and
1141# simply doesn't link to the library otherwise.
1142ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1143           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1144
1145# For Link Time Optimization, the optimisation flags used to compile
1146# individual files are decoupled from those used at link time
1147# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1148# to also update the linker flags based on the target.
1149if env['GCC']:
1150    if sys.platform == 'sunos5':
1151        ccflags['debug'] += ['-gstabs+']
1152    else:
1153        ccflags['debug'] += ['-ggdb3']
1154    ldflags['debug'] += ['-O0']
1155    # opt, fast, prof and perf all share the same cc flags, also add
1156    # the optimization to the ldflags as LTO defers the optimization
1157    # to link time
1158    for target in ['opt', 'fast', 'prof', 'perf']:
1159        ccflags[target] += ['-O3']
1160        ldflags[target] += ['-O3']
1161
1162    ccflags['fast'] += env['LTO_CCFLAGS']
1163    ldflags['fast'] += env['LTO_LDFLAGS']
1164elif env['CLANG']:
1165    ccflags['debug'] += ['-g', '-O0']
1166    # opt, fast, prof and perf all share the same cc flags
1167    for target in ['opt', 'fast', 'prof', 'perf']:
1168        ccflags[target] += ['-O3']
1169else:
1170    print 'Unknown compiler, please fix compiler options'
1171    Exit(1)
1172
1173
1174# To speed things up, we only instantiate the build environments we
1175# need.  We try to identify the needed environment for each target; if
1176# we can't, we fall back on instantiating all the environments just to
1177# be safe.
1178target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1179obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1180              'gpo' : 'perf'}
1181
1182def identifyTarget(t):
1183    ext = t.split('.')[-1]
1184    if ext in target_types:
1185        return ext
1186    if obj2target.has_key(ext):
1187        return obj2target[ext]
1188    match = re.search(r'/tests/([^/]+)/', t)
1189    if match and match.group(1) in target_types:
1190        return match.group(1)
1191    return 'all'
1192
1193needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1194if 'all' in needed_envs:
1195    needed_envs += target_types
1196
1197gem5_root = Dir('.').up().up().abspath
1198def makeEnvirons(target, source, env):
1199    # cause any later Source() calls to be fatal, as a diagnostic.
1200    Source.done()
1201
1202    envList = []
1203
1204    # Debug binary
1205    if 'debug' in needed_envs:
1206        envList.append(
1207            makeEnv(env, 'debug', '.do',
1208                    CCFLAGS = Split(ccflags['debug']),
1209                    CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1210                    LINKFLAGS = Split(ldflags['debug'])))
1211
1212    # Optimized binary
1213    if 'opt' in needed_envs:
1214        envList.append(
1215            makeEnv(env, 'opt', '.o',
1216                    CCFLAGS = Split(ccflags['opt']),
1217                    CPPDEFINES = ['TRACING_ON=1'],
1218                    LINKFLAGS = Split(ldflags['opt'])))
1219
1220    # "Fast" binary
1221    if 'fast' in needed_envs:
1222        envList.append(
1223            makeEnv(env, 'fast', '.fo', strip = True,
1224                    CCFLAGS = Split(ccflags['fast']),
1225                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1226                    LINKFLAGS = Split(ldflags['fast'])))
1227
1228    # Profiled binary using gprof
1229    if 'prof' in needed_envs:
1230        envList.append(
1231            makeEnv(env, 'prof', '.po',
1232                    CCFLAGS = Split(ccflags['prof']),
1233                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1234                    LINKFLAGS = Split(ldflags['prof'])))
1235
1236    # Profiled binary using google-pprof
1237    if 'perf' in needed_envs:
1238        envList.append(
1239            makeEnv(env, 'perf', '.gpo',
1240                    CCFLAGS = Split(ccflags['perf']),
1241                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1242                    LINKFLAGS = Split(ldflags['perf'])))
1243
1244    # Set up the regression tests for each build.
1245    for e in envList:
1246        SConscript(os.path.join(gem5_root, 'tests', 'SConscript'),
1247                   variant_dir = variantd('tests', e.Label),
1248                   exports = { 'env' : e }, duplicate = False)
1249
1250# The MakeEnvirons Builder defers the full dependency collection until
1251# after processing the ISA definition (due to dynamically generated
1252# source files).  Add this dependency to all targets so they will wait
1253# until the environments are completely set up.  Otherwise, a second
1254# process (e.g. -j2 or higher) will try to compile the requested target,
1255# not know how, and fail.
1256env.Append(BUILDERS = {'MakeEnvirons' :
1257                        Builder(action=MakeAction(makeEnvirons,
1258                                                  Transform("ENVIRONS", 1)))})
1259
1260isa_target = env['PHONY_BASE'] + '-deps'
1261environs   = env['PHONY_BASE'] + '-environs'
1262env.Depends('#all-deps',     isa_target)
1263env.Depends('#all-environs', environs)
1264env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1265envSetup = env.MakeEnvirons(environs, isa_target)
1266
1267# make sure no -deps targets occur before all ISAs are complete
1268env.Depends(isa_target, '#all-isas')
1269# likewise for -environs targets and all the -deps targets
1270env.Depends(environs, '#all-deps')
1271