SConscript revision 10388
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 sys
384202Sbinkertn@umich.eduimport zlib
395342Sstever@gmail.com
40955SN/Afrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
414381Sbinkertn@umich.edu
424381Sbinkertn@umich.eduimport SCons
43955SN/A
44955SN/A# This file defines how to build a particular configuration of gem5
45955SN/A# based on variable settings in the 'env' build environment.
464202Sbinkertn@umich.edu
47955SN/AImport('*')
484382Sbinkertn@umich.edu
494382Sbinkertn@umich.edu# Children need to see the environment
504382Sbinkertn@umich.eduExport('env')
515517Snate@binkert.org
525517Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
534762Snate@binkert.org
544762Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
554762Snate@binkert.org
564762Snate@binkert.org########################################################################
574762Snate@binkert.org# Code for adding source files of various types
584762Snate@binkert.org#
594762Snate@binkert.org# When specifying a source file of some type, a set of guards can be
604762Snate@binkert.org# specified for that file.  When get() is used to find the files, if
614762Snate@binkert.org# get specifies a set of filters, only files that match those filters
624762Snate@binkert.org# will be accepted (unspecified filters on files are assumed to be
635522Snate@binkert.org# false).  Current filters are:
645604Snate@binkert.org#     main -- specifies the gem5 main() function
655604Snate@binkert.org#     skip_lib -- do not put this file into the gem5 library
665604Snate@binkert.org#     <unittest> -- unit tests use filters based on the unit test name
674762Snate@binkert.org#
684762Snate@binkert.org# A parent can now be specified for a source file and default filter
694762Snate@binkert.org# values will be retrieved recursively from parents (children override
705522Snate@binkert.org# parents).
715522Snate@binkert.org#
725522Snate@binkert.orgclass SourceMeta(type):
735522Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
745604Snate@binkert.org    particular type and has a get function for finding all functions
755604Snate@binkert.org    of a certain type that match a set of guards'''
764762Snate@binkert.org    def __init__(cls, name, bases, dict):
774762Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
784762Snate@binkert.org        cls.all = []
794762Snate@binkert.org        
805522Snate@binkert.org    def get(cls, **guards):
814762Snate@binkert.org        '''Find all files that match the specified guards.  If a source
824762Snate@binkert.org        file does not specify a flag, the default is False'''
835604Snate@binkert.org        for src in cls.all:
845604Snate@binkert.org            for flag,value in guards.iteritems():
855604Snate@binkert.org                # if the flag is found and has a different value, skip
865604Snate@binkert.org                # this file
875604Snate@binkert.org                if src.all_guards.get(flag, False) != value:
885604Snate@binkert.org                    break
894762Snate@binkert.org            else:
904762Snate@binkert.org                yield src
914762Snate@binkert.org
924762Snate@binkert.orgclass SourceFile(object):
935604Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
944762Snate@binkert.org    This includes, the source node, target node, various manipulations
955522Snate@binkert.org    of those.  A source file also specifies a set of guards which
965522Snate@binkert.org    describing which builds the source file applies to.  A parent can
975522Snate@binkert.org    also be specified to get default guards from'''
984762Snate@binkert.org    __metaclass__ = SourceMeta
994382Sbinkertn@umich.edu    def __init__(self, source, parent=None, **guards):
1004762Snate@binkert.org        self.guards = guards
1014382Sbinkertn@umich.edu        self.parent = parent
1025522Snate@binkert.org
1034381Sbinkertn@umich.edu        tnode = source
1045522Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1054762Snate@binkert.org            tnode = File(source)
1064762Snate@binkert.org
1074762Snate@binkert.org        self.tnode = tnode
1085522Snate@binkert.org        self.snode = tnode.srcnode()
1095522Snate@binkert.org
1105522Snate@binkert.org        for base in type(self).__mro__:
1115522Snate@binkert.org            if issubclass(base, SourceFile):
1125522Snate@binkert.org                base.all.append(self)
1135522Snate@binkert.org
1145522Snate@binkert.org    @property
1155522Snate@binkert.org    def filename(self):
1165522Snate@binkert.org        return str(self.tnode)
1174762Snate@binkert.org
1184762Snate@binkert.org    @property
1194762Snate@binkert.org    def dirname(self):
1204762Snate@binkert.org        return dirname(self.filename)
1214762Snate@binkert.org
1224762Snate@binkert.org    @property
1234762Snate@binkert.org    def basename(self):
1244762Snate@binkert.org        return basename(self.filename)
1254762Snate@binkert.org
1264762Snate@binkert.org    @property
1274762Snate@binkert.org    def extname(self):
1284762Snate@binkert.org        index = self.basename.rfind('.')
1294762Snate@binkert.org        if index <= 0:
1304762Snate@binkert.org            # dot files aren't extensions
1314762Snate@binkert.org            return self.basename, None
1324762Snate@binkert.org
1334762Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1344762Snate@binkert.org
1354762Snate@binkert.org    @property
1364762Snate@binkert.org    def all_guards(self):
1374762Snate@binkert.org        '''find all guards for this object getting default values
1384762Snate@binkert.org        recursively from its parents'''
1394762Snate@binkert.org        guards = {}
1404762Snate@binkert.org        if self.parent:
1414762Snate@binkert.org            guards.update(self.parent.guards)
1424762Snate@binkert.org        guards.update(self.guards)
1434762Snate@binkert.org        return guards
1444762Snate@binkert.org
1454762Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
1464762Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
1474762Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
1484762Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
1494762Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
1504762Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
1514762Snate@binkert.org
152955SN/A    @staticmethod
1535584Snate@binkert.org    def done():
1545584Snate@binkert.org        def disabled(cls, name, *ignored):
1555584Snate@binkert.org            raise RuntimeError("Additional SourceFile '%s'" % name,\
1565584Snate@binkert.org                  "declared, but targets deps are already fixed.")
1575584Snate@binkert.org        SourceFile.__init__ = disabled
1585584Snate@binkert.org
1595584Snate@binkert.org
1605584Snate@binkert.orgclass Source(SourceFile):
1615584Snate@binkert.org    '''Add a c/c++ source file to the build'''
1625584Snate@binkert.org    def __init__(self, source, Werror=True, swig=False, **guards):
1635584Snate@binkert.org        '''specify the source file, and any guards'''
1645584Snate@binkert.org        super(Source, self).__init__(source, **guards)
1655584Snate@binkert.org
1664382Sbinkertn@umich.edu        self.Werror = Werror
1674202Sbinkertn@umich.edu        self.swig = swig
1685522Snate@binkert.org
1694382Sbinkertn@umich.educlass PySource(SourceFile):
1704382Sbinkertn@umich.edu    '''Add a python source file to the named package'''
1714382Sbinkertn@umich.edu    invalid_sym_char = re.compile('[^A-z0-9_]')
1725584Snate@binkert.org    modules = {}
1734382Sbinkertn@umich.edu    tnodes = {}
1744382Sbinkertn@umich.edu    symnames = {}
1754382Sbinkertn@umich.edu
1765192Ssaidi@eecs.umich.edu    def __init__(self, package, source, **guards):
1775192Ssaidi@eecs.umich.edu        '''specify the python package, the source file, and any guards'''
1785192Ssaidi@eecs.umich.edu        super(PySource, self).__init__(source, **guards)
1795192Ssaidi@eecs.umich.edu
1805192Ssaidi@eecs.umich.edu        modname,ext = self.extname
1815192Ssaidi@eecs.umich.edu        assert ext == 'py'
1825192Ssaidi@eecs.umich.edu
1835192Ssaidi@eecs.umich.edu        if package:
1845192Ssaidi@eecs.umich.edu            path = package.split('.')
1855192Ssaidi@eecs.umich.edu        else:
1865192Ssaidi@eecs.umich.edu            path = []
1875192Ssaidi@eecs.umich.edu
1885192Ssaidi@eecs.umich.edu        modpath = path[:]
1895192Ssaidi@eecs.umich.edu        if modname != '__init__':
1905192Ssaidi@eecs.umich.edu            modpath += [ modname ]
1915192Ssaidi@eecs.umich.edu        modpath = '.'.join(modpath)
1925192Ssaidi@eecs.umich.edu
1935192Ssaidi@eecs.umich.edu        arcpath = path + [ self.basename ]
1945192Ssaidi@eecs.umich.edu        abspath = self.snode.abspath
1955192Ssaidi@eecs.umich.edu        if not exists(abspath):
1965192Ssaidi@eecs.umich.edu            abspath = self.tnode.abspath
1975192Ssaidi@eecs.umich.edu
1985192Ssaidi@eecs.umich.edu        self.package = package
1995192Ssaidi@eecs.umich.edu        self.modname = modname
2005192Ssaidi@eecs.umich.edu        self.modpath = modpath
2015192Ssaidi@eecs.umich.edu        self.arcname = joinpath(*arcpath)
2025192Ssaidi@eecs.umich.edu        self.abspath = abspath
2035192Ssaidi@eecs.umich.edu        self.compiled = File(self.filename + 'c')
2045192Ssaidi@eecs.umich.edu        self.cpp = File(self.filename + '.cc')
2055192Ssaidi@eecs.umich.edu        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2065192Ssaidi@eecs.umich.edu
2075192Ssaidi@eecs.umich.edu        PySource.modules[modpath] = self
2084382Sbinkertn@umich.edu        PySource.tnodes[self.tnode] = self
2094382Sbinkertn@umich.edu        PySource.symnames[self.symname] = self
2104382Sbinkertn@umich.edu
2112667Sstever@eecs.umich.educlass SimObject(PySource):
2122667Sstever@eecs.umich.edu    '''Add a SimObject python file as a python source object and add
2132667Sstever@eecs.umich.edu    it to a list of sim object modules'''
2142667Sstever@eecs.umich.edu
2152667Sstever@eecs.umich.edu    fixed = False
2162667Sstever@eecs.umich.edu    modnames = []
2172037SN/A
2182037SN/A    def __init__(self, source, **guards):
2192037SN/A        '''Specify the source file and any guards (automatically in
2204382Sbinkertn@umich.edu        the m5.objects package)'''
2214762Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, **guards)
2225344Sstever@gmail.com        if self.fixed:
2234382Sbinkertn@umich.edu            raise AttributeError, "Too late to call SimObject now."
2245341Sstever@gmail.com
2255341Sstever@gmail.com        bisect.insort_right(SimObject.modnames, self.modname)
2265341Sstever@gmail.com
2275344Sstever@gmail.comclass SwigSource(SourceFile):
2285341Sstever@gmail.com    '''Add a swig file to build'''
2295341Sstever@gmail.com
2305341Sstever@gmail.com    def __init__(self, package, source, **guards):
2314762Snate@binkert.org        '''Specify the python package, the source file, and any guards'''
2325341Sstever@gmail.com        super(SwigSource, self).__init__(source, **guards)
2335344Sstever@gmail.com
2345341Sstever@gmail.com        modname,ext = self.extname
2354773Snate@binkert.org        assert ext == 'i'
2361858SN/A
2371858SN/A        self.module = modname
2381085SN/A        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2394382Sbinkertn@umich.edu        py_file = joinpath(self.dirname, modname + '.py')
2404382Sbinkertn@umich.edu
2414762Snate@binkert.org        self.cc_source = Source(cc_file, swig=True, parent=self)
2424762Snate@binkert.org        self.py_source = PySource(package, py_file, parent=self)
2434762Snate@binkert.org
2445517Snate@binkert.orgclass ProtoBuf(SourceFile):
2455517Snate@binkert.org    '''Add a Protocol Buffer to build'''
2465517Snate@binkert.org
2475517Snate@binkert.org    def __init__(self, source, **guards):
2485517Snate@binkert.org        '''Specify the source file, and any guards'''
2495517Snate@binkert.org        super(ProtoBuf, self).__init__(source, **guards)
2505517Snate@binkert.org
2515517Snate@binkert.org        # Get the file name and the extension
2525517Snate@binkert.org        modname,ext = self.extname
2535517Snate@binkert.org        assert ext == 'proto'
2545517Snate@binkert.org
2555517Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
2565517Snate@binkert.org        # only need to track the source and header.
2575517Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
2585517Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
2595517Snate@binkert.org
2605517Snate@binkert.orgclass UnitTest(object):
2615517Snate@binkert.org    '''Create a UnitTest'''
2625517Snate@binkert.org
2635517Snate@binkert.org    all = []
2645517Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
2655517Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2665517Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2675517Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2685517Snate@binkert.org        target.'''
2695517Snate@binkert.org
2705517Snate@binkert.org        srcs = []
2715517Snate@binkert.org        for src in sources:
2725517Snate@binkert.org            if not isinstance(src, SourceFile):
2735517Snate@binkert.org                src = Source(src, skip_lib=True)
2745517Snate@binkert.org            src.guards[target] = True
2755517Snate@binkert.org            srcs.append(src)
2765517Snate@binkert.org
2775517Snate@binkert.org        self.sources = srcs
2785517Snate@binkert.org        self.target = target
2795517Snate@binkert.org        self.main = kwargs.get('main', False)
2805517Snate@binkert.org        UnitTest.all.append(self)
2815517Snate@binkert.org
2825517Snate@binkert.org# Children should have access
2835517Snate@binkert.orgExport('Source')
2845517Snate@binkert.orgExport('PySource')
2855517Snate@binkert.orgExport('SimObject')
2865517Snate@binkert.orgExport('SwigSource')
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#
2945517Snate@binkert.orgdebug_flags = {}
2955517Snate@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
3005522Snate@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)
3054762Snate@binkert.org    debug_flags[name] = (name, compound, desc)
3065517Snate@binkert.org
3075517Snate@binkert.orgExport('DebugFlag')
3084762Snate@binkert.orgExport('CompoundFlag')
3095517Snate@binkert.org
3104762Snate@binkert.org########################################################################
3115517Snate@binkert.org#
3125517Snate@binkert.org# Set some compiler variables
3135517Snate@binkert.org#
3145517Snate@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
3175517Snate@binkert.org# the corresponding build directory to pick up generated include
3185517Snate@binkert.org# files.
3195517Snate@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
3344762Snate@binkert.orghere = Dir('.').srcnode().abspath
3354762Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3364762Snate@binkert.org    if root == here:
3374762Snate@binkert.org        # we don't want to recurse back into this SConscript
3384762Snate@binkert.org        continue
3394762Snate@binkert.org
3405517Snate@binkert.org    if 'SConscript' in files:
3414762Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3424762Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3434762Snate@binkert.org
3444762Snate@binkert.orgfor extra_dir in extras_dir_list:
3454382Sbinkertn@umich.edu    prefix_len = len(dirname(extra_dir)) + 1
3464382Sbinkertn@umich.edu
3475517Snate@binkert.org    # Also add the corresponding build directory to pick up generated
3485517Snate@binkert.org    # include files.
3495517Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3505517Snate@binkert.org
3515517Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
3525517Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3535517Snate@binkert.org        if 'build' in dirs:
3545517Snate@binkert.org            dirs.remove('build')
3555517Snate@binkert.org
3565517Snate@binkert.org        if 'SConscript' in files:
3575517Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3585517Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3595517Snate@binkert.org
3605517Snate@binkert.orgfor opt in export_vars:
3615517Snate@binkert.org    env.ConfigFile(opt)
3625517Snate@binkert.org
3635517Snate@binkert.orgdef makeTheISA(source, target, env):
3645517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
3655517Snate@binkert.org    target_isa = env['TARGET_ISA']
3665517Snate@binkert.org    def define(isa):
3675517Snate@binkert.org        return isa.upper() + '_ISA'
3685517Snate@binkert.org    
3695517Snate@binkert.org    def namespace(isa):
3705517Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA' 
3714762Snate@binkert.org
3725517Snate@binkert.org
3734382Sbinkertn@umich.edu    code = code_formatter()
3744382Sbinkertn@umich.edu    code('''\
3754762Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3764382Sbinkertn@umich.edu#define __CONFIG_THE_ISA_HH__
3774382Sbinkertn@umich.edu
3785517Snate@binkert.org''')
3794382Sbinkertn@umich.edu
3804382Sbinkertn@umich.edu    for i,isa in enumerate(isas):
3814762Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
3824382Sbinkertn@umich.edu
3834762Snate@binkert.org    code('''
3845517Snate@binkert.org
3854382Sbinkertn@umich.edu#define THE_ISA ${{define(target_isa)}}
3864382Sbinkertn@umich.edu#define TheISA ${{namespace(target_isa)}}
3874762Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
3884762Snate@binkert.org
3894762Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
3904762Snate@binkert.org
3914762Snate@binkert.org    code.write(str(target[0]))
3925517Snate@binkert.org
3935517Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
3945517Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
3955517Snate@binkert.org
3965517Snate@binkert.org########################################################################
3975517Snate@binkert.org#
3985517Snate@binkert.org# Prevent any SimObjects from being added after this point, they
3995517Snate@binkert.org# should all have been added in the SConscripts above
4005517Snate@binkert.org#
4015517Snate@binkert.orgSimObject.fixed = True
4025517Snate@binkert.org
4035517Snate@binkert.orgclass DictImporter(object):
4045517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4055517Snate@binkert.org    map to arbitrary filenames.'''
4065517Snate@binkert.org    def __init__(self, modules):
4075517Snate@binkert.org        self.modules = modules
4085517Snate@binkert.org        self.installed = set()
4095517Snate@binkert.org
4105517Snate@binkert.org    def __del__(self):
4115517Snate@binkert.org        self.unload()
4125517Snate@binkert.org
4135517Snate@binkert.org    def unload(self):
4145517Snate@binkert.org        import sys
4155517Snate@binkert.org        for module in self.installed:
4165517Snate@binkert.org            del sys.modules[module]
4175517Snate@binkert.org        self.installed = set()
4185517Snate@binkert.org
4195517Snate@binkert.org    def find_module(self, fullname, path):
4205517Snate@binkert.org        if fullname == 'm5.defines':
4215517Snate@binkert.org            return self
4225517Snate@binkert.org
4235517Snate@binkert.org        if fullname == 'm5.objects':
4245517Snate@binkert.org            return self
4255517Snate@binkert.org
4265517Snate@binkert.org        if fullname.startswith('m5.internal'):
4275517Snate@binkert.org            return None
4285517Snate@binkert.org
4295517Snate@binkert.org        source = self.modules.get(fullname, None)
4304762Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
4314762Snate@binkert.org            return self
4325517Snate@binkert.org
4335517Snate@binkert.org        return None
4344762Snate@binkert.org
4354762Snate@binkert.org    def load_module(self, fullname):
4364762Snate@binkert.org        mod = imp.new_module(fullname)
4375517Snate@binkert.org        sys.modules[fullname] = mod
4384762Snate@binkert.org        self.installed.add(fullname)
4394762Snate@binkert.org
4404762Snate@binkert.org        mod.__loader__ = self
4415463Snate@binkert.org        if fullname == 'm5.objects':
4425517Snate@binkert.org            mod.__path__ = fullname.split('.')
4434762Snate@binkert.org            return mod
4444762Snate@binkert.org
4454762Snate@binkert.org        if fullname == 'm5.defines':
4464762Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
4474762Snate@binkert.org            return mod
4484762Snate@binkert.org
4495463Snate@binkert.org        source = self.modules[fullname]
4505517Snate@binkert.org        if source.modname == '__init__':
4514762Snate@binkert.org            mod.__path__ = source.modpath
4524762Snate@binkert.org        mod.__file__ = source.abspath
4534762Snate@binkert.org
4545517Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
4555517Snate@binkert.org
4564762Snate@binkert.org        return mod
4574762Snate@binkert.org
4585517Snate@binkert.orgimport m5.SimObject
4594762Snate@binkert.orgimport m5.params
4604762Snate@binkert.orgfrom m5.util import code_formatter
4614762Snate@binkert.org
4624762Snate@binkert.orgm5.SimObject.clear()
4635517Snate@binkert.orgm5.params.clear()
4644762Snate@binkert.org
4654762Snate@binkert.org# install the python importer so we can grab stuff from the source
4664762Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
4674762Snate@binkert.org# else we won't know about them for the rest of the stuff.
4685517Snate@binkert.orgimporter = DictImporter(PySource.modules)
4695517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
4705517Snate@binkert.org
4715517Snate@binkert.org# import all sim objects so we can populate the all_objects list
4725517Snate@binkert.org# make sure that we're working with a list, then let's sort it
4735517Snate@binkert.orgfor modname in SimObject.modnames:
4745517Snate@binkert.org    exec('from m5.objects import %s' % modname)
4755517Snate@binkert.org
4765517Snate@binkert.org# we need to unload all of the currently imported modules so that they
4775517Snate@binkert.org# will be re-imported the next time the sconscript is run
4785517Snate@binkert.orgimporter.unload()
4795517Snate@binkert.orgsys.meta_path.remove(importer)
4805517Snate@binkert.org
4815517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
4825517Snate@binkert.orgall_enums = m5.params.allEnums
4835517Snate@binkert.org
4845517Snate@binkert.orgif m5.SimObject.noCxxHeader:
4855517Snate@binkert.org    print >> sys.stderr, \
4865517Snate@binkert.org        "warning: At least one SimObject lacks a header specification. " \
4875517Snate@binkert.org        "This can cause unexpected results in the generated SWIG " \
4885517Snate@binkert.org        "wrappers."
4895517Snate@binkert.org
4905517Snate@binkert.org# Find param types that need to be explicitly wrapped with swig.
4915517Snate@binkert.org# These will be recognized because the ParamDesc will have a
4925517Snate@binkert.org# swig_decl() method.  Most param types are based on types that don't
4935517Snate@binkert.org# need this, either because they're based on native types (like Int)
4945517Snate@binkert.org# or because they're SimObjects (which get swigged independently).
4955517Snate@binkert.org# For now the only things handled here are VectorParam types.
4965517Snate@binkert.orgparams_to_swig = {}
4975517Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
4985517Snate@binkert.org    for param in obj._params.local.values():
4995517Snate@binkert.org        # load the ptype attribute now because it depends on the
5005517Snate@binkert.org        # current version of SimObject.allClasses, but when scons
5015517Snate@binkert.org        # actually uses the value, all versions of
5025517Snate@binkert.org        # SimObject.allClasses will have been loaded
5035517Snate@binkert.org        param.ptype
5045517Snate@binkert.org
5055517Snate@binkert.org        if not hasattr(param, 'swig_decl'):
5065517Snate@binkert.org            continue
5075517Snate@binkert.org        pname = param.ptype_str
5085517Snate@binkert.org        if pname not in params_to_swig:
5095517Snate@binkert.org            params_to_swig[pname] = param
5105517Snate@binkert.org
5115517Snate@binkert.org########################################################################
5125517Snate@binkert.org#
5135517Snate@binkert.org# calculate extra dependencies
5145517Snate@binkert.org#
5155517Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5165517Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
5175517Snate@binkert.org
5185517Snate@binkert.org########################################################################
5195517Snate@binkert.org#
5205517Snate@binkert.org# Commands for the basic automatically generated python files
5215517Snate@binkert.org#
5225517Snate@binkert.org
5235517Snate@binkert.org# Generate Python file containing a dict specifying the current
5245517Snate@binkert.org# buildEnv flags.
5255517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
5265517Snate@binkert.org    build_env = source[0].get_contents()
5275517Snate@binkert.org
5285517Snate@binkert.org    code = code_formatter()
5295517Snate@binkert.org    code("""
5305517Snate@binkert.orgimport m5.internal
5315517Snate@binkert.orgimport m5.util
5325517Snate@binkert.org
5335517Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
5345610Snate@binkert.org
5355623Snate@binkert.orgcompileDate = m5.internal.core.compileDate
5365623Snate@binkert.org_globals = globals()
5375623Snate@binkert.orgfor key,val in m5.internal.core.__dict__.iteritems():
5385610Snate@binkert.org    if key.startswith('flag_'):
5395517Snate@binkert.org        flag = key[5:]
5405623Snate@binkert.org        _globals[flag] = val
5415623Snate@binkert.orgdel _globals
5425623Snate@binkert.org""")
5435623Snate@binkert.org    code.write(target[0].abspath)
5445623Snate@binkert.org
5455623Snate@binkert.orgdefines_info = Value(build_env)
5465623Snate@binkert.org# Generate a file with all of the compile options in it
5475517Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
5485610Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
5495610Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
5505610Snate@binkert.org
5515610Snate@binkert.org# Generate python file containing info about the M5 source code
5525517Snate@binkert.orgdef makeInfoPyFile(target, source, env):
5535517Snate@binkert.org    code = code_formatter()
5545610Snate@binkert.org    for src in source:
5555610Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
5565517Snate@binkert.org        code('$src = ${{repr(data)}}')
5575517Snate@binkert.org    code.write(str(target[0]))
5585517Snate@binkert.org
5595517Snate@binkert.org# Generate a file that wraps the basic top level files
5605517Snate@binkert.orgenv.Command('python/m5/info.py',
5615517Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
5625517Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
5635517Snate@binkert.orgPySource('m5', 'python/m5/info.py')
5645517Snate@binkert.org
5655517Snate@binkert.org########################################################################
5664762Snate@binkert.org#
5675517Snate@binkert.org# Create all of the SimObject param headers and enum headers
5685517Snate@binkert.org#
5695463Snate@binkert.org
5704762Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
5714762Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5724762Snate@binkert.org
5734382Sbinkertn@umich.edu    name = str(source[0].get_contents())
5745554Snate@binkert.org    obj = sim_objects[name]
5754762Snate@binkert.org
5764382Sbinkertn@umich.edu    code = code_formatter()
5774762Snate@binkert.org    obj.cxx_param_decl(code)
5784382Sbinkertn@umich.edu    code.write(target[0].abspath)
5794762Snate@binkert.org
5804762Snate@binkert.orgdef createParamSwigWrapper(target, source, env):
5814762Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5824762Snate@binkert.org
5834382Sbinkertn@umich.edu    name = str(source[0].get_contents())
5844382Sbinkertn@umich.edu    param = params_to_swig[name]
5854382Sbinkertn@umich.edu
5864382Sbinkertn@umich.edu    code = code_formatter()
5874382Sbinkertn@umich.edu    param.swig_decl(code)
5884382Sbinkertn@umich.edu    code.write(target[0].abspath)
5894762Snate@binkert.org
5904382Sbinkertn@umich.edudef createEnumStrings(target, source, env):
5915554Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5924382Sbinkertn@umich.edu
5934382Sbinkertn@umich.edu    name = str(source[0].get_contents())
5944762Snate@binkert.org    obj = all_enums[name]
5955517Snate@binkert.org
5965517Snate@binkert.org    code = code_formatter()
5975517Snate@binkert.org    obj.cxx_def(code)
5985517Snate@binkert.org    code.write(target[0].abspath)
5995517Snate@binkert.org
6005517Snate@binkert.orgdef createEnumDecls(target, source, env):
6015522Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6025517Snate@binkert.org
6035517Snate@binkert.org    name = str(source[0].get_contents())
6045517Snate@binkert.org    obj = all_enums[name]
6055517Snate@binkert.org
6065517Snate@binkert.org    code = code_formatter()
6075522Snate@binkert.org    obj.cxx_decl(code)
6085522Snate@binkert.org    code.write(target[0].abspath)
6094382Sbinkertn@umich.edu
6105192Ssaidi@eecs.umich.edudef createEnumSwigWrapper(target, source, env):
6115517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6125517Snate@binkert.org
6135517Snate@binkert.org    name = str(source[0].get_contents())
6145517Snate@binkert.org    obj = all_enums[name]
6155517Snate@binkert.org
6165517Snate@binkert.org    code = code_formatter()
6175517Snate@binkert.org    obj.swig_decl(code)
6185517Snate@binkert.org    code.write(target[0].abspath)
6195517Snate@binkert.org
6205517Snate@binkert.orgdef createSimObjectSwigWrapper(target, source, env):
6215517Snate@binkert.org    name = source[0].get_contents()
6225517Snate@binkert.org    obj = sim_objects[name]
6235517Snate@binkert.org
6245517Snate@binkert.org    code = code_formatter()
6255517Snate@binkert.org    obj.swig_decl(code)
6265517Snate@binkert.org    code.write(target[0].abspath)
6275517Snate@binkert.org
6285517Snate@binkert.org# Generate all of the SimObject param C++ struct header files
6295517Snate@binkert.orgparams_hh_files = []
6305517Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
6315517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6325517Snate@binkert.org    extra_deps = [ py_source.tnode ]
6335517Snate@binkert.org
6345517Snate@binkert.org    hh_file = File('params/%s.hh' % name)
6355517Snate@binkert.org    params_hh_files.append(hh_file)
6365517Snate@binkert.org    env.Command(hh_file, Value(name),
6375517Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6385517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
6395517Snate@binkert.org
6405517Snate@binkert.org# Generate any needed param SWIG wrapper files
6415517Snate@binkert.orgparams_i_files = []
6425517Snate@binkert.orgfor name,param in params_to_swig.iteritems():
6435517Snate@binkert.org    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
6445517Snate@binkert.org    params_i_files.append(i_file)
6455517Snate@binkert.org    env.Command(i_file, Value(name),
6465517Snate@binkert.org                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
6475517Snate@binkert.org    env.Depends(i_file, depends)
6485517Snate@binkert.org    SwigSource('m5.internal', i_file)
6495517Snate@binkert.org
6505517Snate@binkert.org# Generate all enum header files
6515517Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
6525517Snate@binkert.org    py_source = PySource.modules[enum.__module__]
6535517Snate@binkert.org    extra_deps = [ py_source.tnode ]
6545517Snate@binkert.org
6555517Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
6565517Snate@binkert.org    env.Command(cc_file, Value(name),
6575517Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
6585517Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
6595517Snate@binkert.org    Source(cc_file)
6605517Snate@binkert.org
6615517Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
6625517Snate@binkert.org    env.Command(hh_file, Value(name),
6635517Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
6645517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
6655517Snate@binkert.org
6665517Snate@binkert.org    i_file = File('python/m5/internal/enum_%s.i' % name)
6675517Snate@binkert.org    env.Command(i_file, Value(name),
6685517Snate@binkert.org                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
6695517Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
6705517Snate@binkert.org    SwigSource('m5.internal', i_file)
6715517Snate@binkert.org
6725517Snate@binkert.org# Generate SimObject SWIG wrapper files
6735517Snate@binkert.orgfor name,simobj in sim_objects.iteritems():
6745517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6755517Snate@binkert.org    extra_deps = [ py_source.tnode ]
6765517Snate@binkert.org
6775517Snate@binkert.org    i_file = File('python/m5/internal/param_%s.i' % name)
6785517Snate@binkert.org    env.Command(i_file, Value(name),
6795517Snate@binkert.org                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
6805517Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
6815517Snate@binkert.org    SwigSource('m5.internal', i_file)
6825517Snate@binkert.org
6835517Snate@binkert.org# Generate the main swig init file
6845517Snate@binkert.orgdef makeEmbeddedSwigInit(target, source, env):
6855517Snate@binkert.org    code = code_formatter()
6865517Snate@binkert.org    module = source[0].get_contents()
6875517Snate@binkert.org    code('''\
6885517Snate@binkert.org#include "sim/init.hh"
6895517Snate@binkert.org
6905517Snate@binkert.orgextern "C" {
6915517Snate@binkert.org    void init_${module}();
6925517Snate@binkert.org}
6935517Snate@binkert.org
6945517Snate@binkert.orgEmbeddedSwig embed_swig_${module}(init_${module});
6955517Snate@binkert.org''')
6965517Snate@binkert.org    code.write(str(target[0]))
6975517Snate@binkert.org    
6985517Snate@binkert.org# Build all swig modules
6995517Snate@binkert.orgfor swig in SwigSource.all:
7005517Snate@binkert.org    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
7015517Snate@binkert.org                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
7025517Snate@binkert.org                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
7035517Snate@binkert.org    cc_file = str(swig.tnode)
7045517Snate@binkert.org    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
7055517Snate@binkert.org    env.Command(init_file, Value(swig.module),
7065517Snate@binkert.org                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
7075517Snate@binkert.org    Source(init_file, **swig.guards)
7085517Snate@binkert.org
7095517Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
7105517Snate@binkert.orgif env['HAVE_PROTOBUF']:
7115517Snate@binkert.org    for proto in ProtoBuf.all:
7125517Snate@binkert.org        # Use both the source and header as the target, and the .proto
7135517Snate@binkert.org        # file as the source. When executing the protoc compiler, also
7145517Snate@binkert.org        # specify the proto_path to avoid having the generated files
7155517Snate@binkert.org        # include the path.
7165517Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
7175517Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
7185517Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
7195517Snate@binkert.org                               Transform("PROTOC")))
7205517Snate@binkert.org
7215517Snate@binkert.org        # Add the C++ source file
7225517Snate@binkert.org        Source(proto.cc_file, **proto.guards)
7235517Snate@binkert.orgelif ProtoBuf.all:
7245517Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
7255517Snate@binkert.org    Exit(1)
7265517Snate@binkert.org
7275517Snate@binkert.org#
7285517Snate@binkert.org# Handle debug flags
7295517Snate@binkert.org#
7305517Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
7315517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
7325517Snate@binkert.org
7335517Snate@binkert.org    val = eval(source[0].get_contents())
7345517Snate@binkert.org    name, compound, desc = val
7355517Snate@binkert.org    compound = list(sorted(compound))
7365517Snate@binkert.org
7375517Snate@binkert.org    code = code_formatter()
7385517Snate@binkert.org
7395517Snate@binkert.org    # file header
7405517Snate@binkert.org    code('''
7415517Snate@binkert.org/*
7425517Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated
7435517Snate@binkert.org */
7445517Snate@binkert.org
7455517Snate@binkert.org#include "base/debug.hh"
7465517Snate@binkert.org''')
7475517Snate@binkert.org
7485517Snate@binkert.org    for flag in compound:
7495517Snate@binkert.org        code('#include "debug/$flag.hh"')
7505517Snate@binkert.org    code()
7515517Snate@binkert.org    code('namespace Debug {')
7525517Snate@binkert.org    code()
7535517Snate@binkert.org
7545517Snate@binkert.org    if not compound:
7555517Snate@binkert.org        code('SimpleFlag $name("$name", "$desc");')
7565517Snate@binkert.org    else:
7575517Snate@binkert.org        code('CompoundFlag $name("$name", "$desc",')
7585517Snate@binkert.org        code.indent()
7595517Snate@binkert.org        last = len(compound) - 1
7605517Snate@binkert.org        for i,flag in enumerate(compound):
7615517Snate@binkert.org            if i != last:
7625517Snate@binkert.org                code('$flag,')
7635517Snate@binkert.org            else:
7645517Snate@binkert.org                code('$flag);')
7655517Snate@binkert.org        code.dedent()
7665517Snate@binkert.org
7675517Snate@binkert.org    code()
7685517Snate@binkert.org    code('} // namespace Debug')
7695517Snate@binkert.org
7705517Snate@binkert.org    code.write(str(target[0]))
7715517Snate@binkert.org
7725517Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
7735517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
7745517Snate@binkert.org
7755517Snate@binkert.org    val = eval(source[0].get_contents())
7765517Snate@binkert.org    name, compound, desc = val
7775517Snate@binkert.org
7785517Snate@binkert.org    code = code_formatter()
7795517Snate@binkert.org
7805517Snate@binkert.org    # file header boilerplate
7815517Snate@binkert.org    code('''\
7825517Snate@binkert.org/*
7835517Snate@binkert.org * DO NOT EDIT THIS FILE!
7845517Snate@binkert.org *
7855517Snate@binkert.org * Automatically generated by SCons
7865517Snate@binkert.org */
7875517Snate@binkert.org
7885517Snate@binkert.org#ifndef __DEBUG_${name}_HH__
7895517Snate@binkert.org#define __DEBUG_${name}_HH__
7905517Snate@binkert.org
7915517Snate@binkert.orgnamespace Debug {
7925517Snate@binkert.org''')
7935517Snate@binkert.org
7945517Snate@binkert.org    if compound:
7955517Snate@binkert.org        code('class CompoundFlag;')
7965517Snate@binkert.org    code('class SimpleFlag;')
7975517Snate@binkert.org
7985517Snate@binkert.org    if compound:
7995517Snate@binkert.org        code('extern CompoundFlag $name;')
8005517Snate@binkert.org        for flag in compound:
8015517Snate@binkert.org            code('extern SimpleFlag $flag;')
8025192Ssaidi@eecs.umich.edu    else:
8035517Snate@binkert.org        code('extern SimpleFlag $name;')
8045192Ssaidi@eecs.umich.edu
8055192Ssaidi@eecs.umich.edu    code('''
8065517Snate@binkert.org}
8075517Snate@binkert.org
8085192Ssaidi@eecs.umich.edu#endif // __DEBUG_${name}_HH__
8095192Ssaidi@eecs.umich.edu''')
8105456Ssaidi@eecs.umich.edu
8115517Snate@binkert.org    code.write(str(target[0]))
8125517Snate@binkert.org
8135517Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
8145517Snate@binkert.org    n, compound, desc = flag
8155517Snate@binkert.org    assert n == name
8165517Snate@binkert.org
8175517Snate@binkert.org    env.Command('debug/%s.hh' % name, Value(flag),
8185517Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
8195517Snate@binkert.org    env.Command('debug/%s.cc' % name, Value(flag),
8205517Snate@binkert.org                MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
8215517Snate@binkert.org    Source('debug/%s.cc' % name)
8225517Snate@binkert.org
8235517Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
8245517Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
8255517Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
8265517Snate@binkert.org# byte code, compress it, and then generate a c++ file that
8275517Snate@binkert.org# inserts the result into an array.
8285517Snate@binkert.orgdef embedPyFile(target, source, env):
8295517Snate@binkert.org    def c_str(string):
8305517Snate@binkert.org        if string is None:
8315517Snate@binkert.org            return "0"
8325517Snate@binkert.org        return '"%s"' % string
8335517Snate@binkert.org
8345517Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
8355517Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
8365517Snate@binkert.org    as just bytes with a label in the data section'''
8375517Snate@binkert.org
8385517Snate@binkert.org    src = file(str(source[0]), 'r').read()
8395517Snate@binkert.org
8405517Snate@binkert.org    pysource = PySource.tnodes[source[0]]
8415517Snate@binkert.org    compiled = compile(src, pysource.abspath, 'exec')
8425517Snate@binkert.org    marshalled = marshal.dumps(compiled)
8435456Ssaidi@eecs.umich.edu    compressed = zlib.compress(marshalled)
8445461Snate@binkert.org    data = compressed
8455517Snate@binkert.org    sym = pysource.symname
8465456Ssaidi@eecs.umich.edu
8475522Snate@binkert.org    code = code_formatter()
8485522Snate@binkert.org    code('''\
8495522Snate@binkert.org#include "sim/init.hh"
8505522Snate@binkert.org
8515522Snate@binkert.orgnamespace {
8525522Snate@binkert.org
8535522Snate@binkert.orgconst uint8_t data_${sym}[] = {
8545522Snate@binkert.org''')
8555522Snate@binkert.org    code.indent()
8565517Snate@binkert.org    step = 16
8575522Snate@binkert.org    for i in xrange(0, len(data), step):
8585522Snate@binkert.org        x = array.array('B', data[i:i+step])
8595522Snate@binkert.org        code(''.join('%d,' % d for d in x))
8605522Snate@binkert.org    code.dedent()
8615517Snate@binkert.org    
8625522Snate@binkert.org    code('''};
8635522Snate@binkert.org
8645517Snate@binkert.orgEmbeddedPython embedded_${sym}(
8655522Snate@binkert.org    ${{c_str(pysource.arcname)}},
8665604Snate@binkert.org    ${{c_str(pysource.abspath)}},
8675522Snate@binkert.org    ${{c_str(pysource.modpath)}},
8685522Snate@binkert.org    data_${sym},
8695522Snate@binkert.org    ${{len(data)}},
8705517Snate@binkert.org    ${{len(marshalled)}});
8715522Snate@binkert.org
8725522Snate@binkert.org} // anonymous namespace
8735522Snate@binkert.org''')
8745522Snate@binkert.org    code.write(str(target[0]))
8755522Snate@binkert.org
8765522Snate@binkert.orgfor source in PySource.all:
8775522Snate@binkert.org    env.Command(source.cpp, source.tnode, 
8785522Snate@binkert.org                MakeAction(embedPyFile, Transform("EMBED PY")))
8795522Snate@binkert.org    Source(source.cpp)
8805522Snate@binkert.org
8815522Snate@binkert.org########################################################################
8825522Snate@binkert.org#
8835522Snate@binkert.org# Define binaries.  Each different build type (debug, opt, etc.) gets
8845522Snate@binkert.org# a slightly different build environment.
8855522Snate@binkert.org#
8865522Snate@binkert.org
8875522Snate@binkert.org# List of constructed environments to pass back to SConstruct
8885522Snate@binkert.orgdate_source = Source('base/date.cc', skip_lib=True)
8895522Snate@binkert.org
8904382Sbinkertn@umich.edu# Capture this directory for the closure makeEnv, otherwise when it is
8915522Snate@binkert.org# called, it won't know what directory it should use.
8925522Snate@binkert.orgvariant_dir = Dir('.').path
8934382Sbinkertn@umich.edudef variant(*path):
8945522Snate@binkert.org    return os.path.join(variant_dir, *path)
8955522Snate@binkert.orgdef variantd(*path):
8965522Snate@binkert.org    return variant(*path)+'/'
8975522Snate@binkert.org
8985522Snate@binkert.org# Function to create a new build environment as clone of current
8995522Snate@binkert.org# environment 'env' with modified object suffix and optional stripped
9005522Snate@binkert.org# binary.  Additional keyword arguments are appended to corresponding
9015522Snate@binkert.org# build environment vars.
9025522Snate@binkert.orgdef makeEnv(env, label, objsfx, strip = False, **kwargs):
9035522Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
9044382Sbinkertn@umich.edu    # name.  Use '_' instead.
9055522Snate@binkert.org    libname = variant('gem5_' + label)
9065522Snate@binkert.org    exename = variant('gem5.' + label)
9075522Snate@binkert.org    secondary_exename = variant('m5.' + label)
9085522Snate@binkert.org
9095522Snate@binkert.org    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
9105522Snate@binkert.org    new_env.Label = label
9115522Snate@binkert.org    new_env.Append(**kwargs)
9125522Snate@binkert.org
9135522Snate@binkert.org    swig_env = new_env.Clone()
9145522Snate@binkert.org
9155522Snate@binkert.org    # Both gcc and clang have issues with unused labels and values in
9165522Snate@binkert.org    # the SWIG generated code
9175522Snate@binkert.org    swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
9185522Snate@binkert.org
9195522Snate@binkert.org    # Add additional warnings here that should not be applied to
9205522Snate@binkert.org    # the SWIG generated code
9215522Snate@binkert.org    new_env.Append(CXXFLAGS='-Wmissing-declarations')
9225522Snate@binkert.org
9235522Snate@binkert.org    if env['GCC']:
9245522Snate@binkert.org        # Depending on the SWIG version, we also need to supress
9255522Snate@binkert.org        # warnings about uninitialized variables and missing field
9265522Snate@binkert.org        # initializers.
9275522Snate@binkert.org        swig_env.Append(CCFLAGS=['-Wno-uninitialized',
9285522Snate@binkert.org                                 '-Wno-missing-field-initializers',
9295522Snate@binkert.org                                 '-Wno-unused-but-set-variable'])
9305522Snate@binkert.org
9315522Snate@binkert.org        # If gcc supports it, also warn for deletion of derived
9325522Snate@binkert.org        # classes with non-virtual desctructors. For gcc >= 4.7 we
9335522Snate@binkert.org        # also have to disable warnings about the SWIG code having
9345522Snate@binkert.org        # potentially uninitialized variables.
9355522Snate@binkert.org        if compareVersions(env['GCC_VERSION'], '4.7') >= 0:
9364382Sbinkertn@umich.edu            new_env.Append(CXXFLAGS='-Wdelete-non-virtual-dtor')
9374382Sbinkertn@umich.edu            swig_env.Append(CCFLAGS='-Wno-maybe-uninitialized')
9384382Sbinkertn@umich.edu    if env['CLANG']:
9394382Sbinkertn@umich.edu        # Always enable the warning for deletion of derived classes
9404382Sbinkertn@umich.edu        # with non-virtual destructors
9414382Sbinkertn@umich.edu        new_env.Append(CXXFLAGS=['-Wdelete-non-virtual-dtor'])
9424382Sbinkertn@umich.edu
9434382Sbinkertn@umich.edu        swig_env.Append(CCFLAGS=[
9444382Sbinkertn@umich.edu                # Some versions of SWIG can return uninitialized values
9454382Sbinkertn@umich.edu                '-Wno-sometimes-uninitialized',
946955SN/A                # Register storage is requested in a lot of places in
947955SN/A                # SWIG-generated code.
948955SN/A                '-Wno-deprecated-register',
949955SN/A                ])
9501108SN/A
9515601Snate@binkert.org    werror_env = new_env.Clone()
9525601Snate@binkert.org    werror_env.Append(CCFLAGS='-Werror')
9535601Snate@binkert.org
9545601Snate@binkert.org    def make_obj(source, static, extra_deps = None):
9555601Snate@binkert.org        '''This function adds the specified source to the correct
9565601Snate@binkert.org        build environment, and returns the corresponding SCons Object
9575601Snate@binkert.org        nodes'''
9585456Ssaidi@eecs.umich.edu
959955SN/A        if source.swig:
960955SN/A            env = swig_env
9615601Snate@binkert.org        elif source.Werror:
9625456Ssaidi@eecs.umich.edu            env = werror_env
9635456Ssaidi@eecs.umich.edu        else:
9645456Ssaidi@eecs.umich.edu            env = new_env
9655456Ssaidi@eecs.umich.edu
9665601Snate@binkert.org        if static:
9675456Ssaidi@eecs.umich.edu            obj = env.StaticObject(source.tnode)
968955SN/A        else:
9695456Ssaidi@eecs.umich.edu            obj = env.SharedObject(source.tnode)
9705601Snate@binkert.org
971955SN/A        if extra_deps:
972955SN/A            env.Depends(obj, extra_deps)
9732655Sstever@eecs.umich.edu
9742655Sstever@eecs.umich.edu        return obj
9752655Sstever@eecs.umich.edu
9762655Sstever@eecs.umich.edu    static_objs = \
9772655Sstever@eecs.umich.edu        [ make_obj(s, True) for s in Source.get(main=False, skip_lib=False) ]
9785601Snate@binkert.org    shared_objs = \
9795601Snate@binkert.org        [ make_obj(s, False) for s in Source.get(main=False, skip_lib=False) ]
9805601Snate@binkert.org
9815601Snate@binkert.org    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
9825522Snate@binkert.org    static_objs.append(static_date)
9835601Snate@binkert.org    
9845601Snate@binkert.org    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
9855601Snate@binkert.org    shared_objs.append(shared_date)
9865601Snate@binkert.org
9875601Snate@binkert.org    # First make a library of everything but main() so other programs can
9885559Snate@binkert.org    # link against m5.
9895559Snate@binkert.org    static_lib = new_env.StaticLibrary(libname, static_objs)
9905559Snate@binkert.org    shared_lib = new_env.SharedLibrary(libname, shared_objs)
9915559Snate@binkert.org
9925601Snate@binkert.org    # Now link a stub with main() and the static library.
9935601Snate@binkert.org    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
9945601Snate@binkert.org
9955601Snate@binkert.org    for test in UnitTest.all:
9965601Snate@binkert.org        flags = { test.target : True }
9975554Snate@binkert.org        test_sources = Source.get(**flags)
9985522Snate@binkert.org        test_objs = [ make_obj(s, static=True) for s in test_sources ]
9995522Snate@binkert.org        if test.main:
10005601Snate@binkert.org            test_objs += main_objs
10015601Snate@binkert.org        path = variant('unittest/%s.%s' % (test.target, label))
10025522Snate@binkert.org        new_env.Program(path, test_objs + static_objs)
10035584Snate@binkert.org
10045601Snate@binkert.org    progname = exename
10055601Snate@binkert.org    if strip:
10065584Snate@binkert.org        progname += '.unstripped'
10075601Snate@binkert.org
10085601Snate@binkert.org    targets = new_env.Program(progname, main_objs + static_objs)
10092655Sstever@eecs.umich.edu
10105601Snate@binkert.org    if strip:
10115601Snate@binkert.org        if sys.platform == 'sunos5':
10124007Ssaidi@eecs.umich.edu            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
10134596Sbinkertn@umich.edu        else:
10144007Ssaidi@eecs.umich.edu            cmd = 'strip $SOURCE -o $TARGET'
10154596Sbinkertn@umich.edu        targets = new_env.Command(exename, progname,
10165601Snate@binkert.org                    MakeAction(cmd, Transform("STRIP")))
10175522Snate@binkert.org
10185601Snate@binkert.org    new_env.Command(secondary_exename, exename,
10195522Snate@binkert.org            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
10205601Snate@binkert.org
10215601Snate@binkert.org    new_env.M5Binary = targets[0]
10222655Sstever@eecs.umich.edu    return new_env
1023955SN/A
10243918Ssaidi@eecs.umich.edu# Start out with the compiler flags common to all compilers,
10253918Ssaidi@eecs.umich.edu# i.e. they all use -g for opt and -g -pg for prof
10263918Ssaidi@eecs.umich.educcflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
10273918Ssaidi@eecs.umich.edu           'perf' : ['-g']}
10283918Ssaidi@eecs.umich.edu
10293918Ssaidi@eecs.umich.edu# Start out with the linker flags common to all linkers, i.e. -pg for
10303918Ssaidi@eecs.umich.edu# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
10313918Ssaidi@eecs.umich.edu# no-as-needed and as-needed as the binutils linker is too clever and
10323918Ssaidi@eecs.umich.edu# simply doesn't link to the library otherwise.
10333918Ssaidi@eecs.umich.eduldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
10343918Ssaidi@eecs.umich.edu           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
10353918Ssaidi@eecs.umich.edu
10363918Ssaidi@eecs.umich.edu# For Link Time Optimization, the optimisation flags used to compile
10373918Ssaidi@eecs.umich.edu# individual files are decoupled from those used at link time
10383940Ssaidi@eecs.umich.edu# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
10393940Ssaidi@eecs.umich.edu# to also update the linker flags based on the target.
10403940Ssaidi@eecs.umich.eduif env['GCC']:
10413942Ssaidi@eecs.umich.edu    if sys.platform == 'sunos5':
10423940Ssaidi@eecs.umich.edu        ccflags['debug'] += ['-gstabs+']
10433515Ssaidi@eecs.umich.edu    else:
10443918Ssaidi@eecs.umich.edu        ccflags['debug'] += ['-ggdb3']
10454762Snate@binkert.org    ldflags['debug'] += ['-O0']
10463515Ssaidi@eecs.umich.edu    # opt, fast, prof and perf all share the same cc flags, also add
10472655Sstever@eecs.umich.edu    # the optimization to the ldflags as LTO defers the optimization
10483918Ssaidi@eecs.umich.edu    # to link time
10493619Sbinkertn@umich.edu    for target in ['opt', 'fast', 'prof', 'perf']:
1050955SN/A        ccflags[target] += ['-O3']
1051955SN/A        ldflags[target] += ['-O3']
10522655Sstever@eecs.umich.edu
10533918Ssaidi@eecs.umich.edu    ccflags['fast'] += env['LTO_CCFLAGS']
10543619Sbinkertn@umich.edu    ldflags['fast'] += env['LTO_LDFLAGS']
1055955SN/Aelif env['CLANG']:
1056955SN/A    ccflags['debug'] += ['-g', '-O0']
10572655Sstever@eecs.umich.edu    # opt, fast, prof and perf all share the same cc flags
10583918Ssaidi@eecs.umich.edu    for target in ['opt', 'fast', 'prof', 'perf']:
10593619Sbinkertn@umich.edu        ccflags[target] += ['-O3']
1060955SN/Aelse:
1061955SN/A    print 'Unknown compiler, please fix compiler options'
10622655Sstever@eecs.umich.edu    Exit(1)
10633918Ssaidi@eecs.umich.edu
10643683Sstever@eecs.umich.edu
10652655Sstever@eecs.umich.edu# To speed things up, we only instantiate the build environments we
10661869SN/A# need.  We try to identify the needed environment for each target; if
10671869SN/A# we can't, we fall back on instantiating all the environments just to
1068# be safe.
1069target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1070obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1071              'gpo' : 'perf'}
1072
1073def identifyTarget(t):
1074    ext = t.split('.')[-1]
1075    if ext in target_types:
1076        return ext
1077    if obj2target.has_key(ext):
1078        return obj2target[ext]
1079    match = re.search(r'/tests/([^/]+)/', t)
1080    if match and match.group(1) in target_types:
1081        return match.group(1)
1082    return 'all'
1083
1084needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1085if 'all' in needed_envs:
1086    needed_envs += target_types
1087
1088gem5_root = Dir('.').up().up().abspath
1089def makeEnvirons(target, source, env):
1090    # cause any later Source() calls to be fatal, as a diagnostic.
1091    Source.done()
1092
1093    envList = []
1094
1095    # Debug binary
1096    if 'debug' in needed_envs:
1097        envList.append(
1098            makeEnv(env, 'debug', '.do',
1099                    CCFLAGS = Split(ccflags['debug']),
1100                    CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1101                    LINKFLAGS = Split(ldflags['debug'])))
1102
1103    # Optimized binary
1104    if 'opt' in needed_envs:
1105        envList.append(
1106            makeEnv(env, 'opt', '.o',
1107                    CCFLAGS = Split(ccflags['opt']),
1108                    CPPDEFINES = ['TRACING_ON=1'],
1109                    LINKFLAGS = Split(ldflags['opt'])))
1110
1111    # "Fast" binary
1112    if 'fast' in needed_envs:
1113        envList.append(
1114            makeEnv(env, 'fast', '.fo', strip = True,
1115                    CCFLAGS = Split(ccflags['fast']),
1116                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1117                    LINKFLAGS = Split(ldflags['fast'])))
1118
1119    # Profiled binary using gprof
1120    if 'prof' in needed_envs:
1121        envList.append(
1122            makeEnv(env, 'prof', '.po',
1123                    CCFLAGS = Split(ccflags['prof']),
1124                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1125                    LINKFLAGS = Split(ldflags['prof'])))
1126
1127    # Profiled binary using google-pprof
1128    if 'perf' in needed_envs:
1129        envList.append(
1130            makeEnv(env, 'perf', '.gpo',
1131                    CCFLAGS = Split(ccflags['perf']),
1132                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1133                    LINKFLAGS = Split(ldflags['perf'])))
1134
1135    # Set up the regression tests for each build.
1136    for e in envList:
1137        SConscript(os.path.join(gem5_root, 'tests', 'SConscript'),
1138                   variant_dir = variantd('tests', e.Label),
1139                   exports = { 'env' : e }, duplicate = False)
1140
1141# The MakeEnvirons Builder defers the full dependency collection until
1142# after processing the ISA definition (due to dynamically generated
1143# source files).  Add this dependency to all targets so they will wait
1144# until the environments are completely set up.  Otherwise, a second
1145# process (e.g. -j2 or higher) will try to compile the requested target,
1146# not know how, and fail.
1147env.Append(BUILDERS = {'MakeEnvirons' :
1148                        Builder(action=MakeAction(makeEnvirons,
1149                                                  Transform("ENVIRONS", 1)))})
1150
1151isa_target = env['PHONY_BASE'] + '-deps'
1152environs   = env['PHONY_BASE'] + '-environs'
1153env.Depends('#all-deps',     isa_target)
1154env.Depends('#all-environs', environs)
1155env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1156envSetup = env.MakeEnvirons(environs, isa_target)
1157
1158# make sure no -deps targets occur before all ISAs are complete
1159env.Depends(isa_target, '#all-isas')
1160# likewise for -environs targets and all the -deps targets
1161env.Depends(environs, '#all-deps')
1162