SConscript revision 10453
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
526654Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
535517Snate@binkert.org
547674Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
557674Snate@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
696143Snate@binkert.org#
706143Snate@binkert.org# A parent can now be specified for a source file and default filter
714762Snate@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
937065Snate@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__:
1136143Snate@binkert.org            if issubclass(base, SourceFile):
1146143Snate@binkert.org                base.all.append(self)
1155522Snate@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
1246143Snate@binkert.org    @property
1256143Snate@binkert.org    def basename(self):
1265522Snate@binkert.org        return basename(self.filename)
1275522Snate@binkert.org
1285522Snate@binkert.org    @property
1295522Snate@binkert.org    def extname(self):
1305604Snate@binkert.org        index = self.basename.rfind('.')
1315604Snate@binkert.org        if index <= 0:
1326143Snate@binkert.org            # dot files aren't extensions
1336143Snate@binkert.org            return self.basename, None
1344762Snate@binkert.org
1354762Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1366143Snate@binkert.org
1376727Ssteve.reinhardt@amd.com    @property
1386727Ssteve.reinhardt@amd.com    def all_guards(self):
1396727Ssteve.reinhardt@amd.com        '''find all guards for this object getting default values
1404762Snate@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)
1456727Ssteve.reinhardt@amd.com        return guards
1466143Snate@binkert.org
1477674Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
1487674Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
1495604Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
1506143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
1516143Snate@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
1546143Snate@binkert.org    @staticmethod
1554762Snate@binkert.org    def done():
1564762Snate@binkert.org        def disabled(cls, name, *ignored):
1574762Snate@binkert.org            raise RuntimeError("Additional SourceFile '%s'" % name,\
1586143Snate@binkert.org                  "declared, but targets deps are already fixed.")
1596143Snate@binkert.org        SourceFile.__init__ = disabled
1604762Snate@binkert.org
1616143Snate@binkert.org
1626143Snate@binkert.orgclass Source(SourceFile):
1636143Snate@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
1694762Snate@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)
1816143Snate@binkert.org
1826143Snate@binkert.org        modname,ext = self.extname
183955SN/A        assert ext == 'py'
1845584Snate@binkert.org
1855584Snate@binkert.org        if package:
1865584Snate@binkert.org            path = package.split('.')
1875584Snate@binkert.org        else:
1886143Snate@binkert.org            path = []
1896143Snate@binkert.org
1906143Snate@binkert.org        modpath = path[:]
1915584Snate@binkert.org        if modname != '__init__':
1924382Sbinkertn@umich.edu            modpath += [ modname ]
1934202Sbinkertn@umich.edu        modpath = '.'.join(modpath)
1944382Sbinkertn@umich.edu
1954382Sbinkertn@umich.edu        arcpath = path + [ self.basename ]
1964382Sbinkertn@umich.edu        abspath = self.snode.abspath
1975584Snate@binkert.org        if not exists(abspath):
1984382Sbinkertn@umich.edu            abspath = self.tnode.abspath
1994382Sbinkertn@umich.edu
2004382Sbinkertn@umich.edu        self.package = package
2015192Ssaidi@eecs.umich.edu        self.modname = modname
2025192Ssaidi@eecs.umich.edu        self.modpath = modpath
2035799Snate@binkert.org        self.arcname = joinpath(*arcpath)
2045799Snate@binkert.org        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)
2085192Ssaidi@eecs.umich.edu
2095799Snate@binkert.org        PySource.modules[modpath] = self
2105799Snate@binkert.org        PySource.tnodes[self.tnode] = self
2115192Ssaidi@eecs.umich.edu        PySource.symnames[self.symname] = self
2125192Ssaidi@eecs.umich.edu
2135192Ssaidi@eecs.umich.educlass SimObject(PySource):
2145799Snate@binkert.org    '''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 = []
2195192Ssaidi@eecs.umich.edu
2205192Ssaidi@eecs.umich.edu    def __init__(self, source, **guards):
2214382Sbinkertn@umich.edu        '''Specify the source file and any guards (automatically in
2224382Sbinkertn@umich.edu        the m5.objects package)'''
2234382Sbinkertn@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)
2282667Sstever@eecs.umich.edu
2292667Sstever@eecs.umich.educlass SwigSource(SourceFile):
2305742Snate@binkert.org    '''Add a swig file to build'''
2315742Snate@binkert.org
2325742Snate@binkert.org    def __init__(self, package, source, **guards):
2335793Snate@binkert.org        '''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'
2384382Sbinkertn@umich.edu
2394762Snate@binkert.org        self.module = modname
2405344Sstever@gmail.com        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2414382Sbinkertn@umich.edu        py_file = joinpath(self.dirname, modname + '.py')
2425341Sstever@gmail.com
2435742Snate@binkert.org        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'''
2484762Snate@binkert.org
2495742Snate@binkert.org    def __init__(self, source, **guards):
2505742Snate@binkert.org        '''Specify the source file, and any guards'''
2517722Sgblack@eecs.umich.edu        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'
2565341Sstever@gmail.com
2575742Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
2587722Sgblack@eecs.umich.edu        # only need to track the source and header.
2594773Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
2606108Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
2611858SN/A
2621085SN/Aclass UnitTest(object):
2636658Snate@binkert.org    '''Create a UnitTest'''
2646658Snate@binkert.org
2657673Snate@binkert.org    all = []
2666658Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
2676658Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2686658Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2696658Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2706658Snate@binkert.org        target.'''
2716658Snate@binkert.org
2726658Snate@binkert.org        srcs = []
2737673Snate@binkert.org        for src in sources:
2747673Snate@binkert.org            if not isinstance(src, SourceFile):
2757673Snate@binkert.org                src = Source(src, skip_lib=True)
2767673Snate@binkert.org            src.guards[target] = True
2777673Snate@binkert.org            srcs.append(src)
2787673Snate@binkert.org
2797673Snate@binkert.org        self.sources = srcs
2806658Snate@binkert.org        self.target = target
2817673Snate@binkert.org        self.main = kwargs.get('main', False)
2827673Snate@binkert.org        UnitTest.all.append(self)
2837673Snate@binkert.org
2847673Snate@binkert.org# Children should have access
2857673Snate@binkert.orgExport('Source')
2867673Snate@binkert.orgExport('PySource')
2877673Snate@binkert.orgExport('SimObject')
2887673Snate@binkert.orgExport('SwigSource')
2897673Snate@binkert.orgExport('ProtoBuf')
2907673Snate@binkert.orgExport('UnitTest')
2916658Snate@binkert.org
2927756SAli.Saidi@ARM.com########################################################################
2937816Ssteve.reinhardt@amd.com#
2946658Snate@binkert.org# Debug Flags
2954382Sbinkertn@umich.edu#
2964382Sbinkertn@umich.edudebug_flags = {}
2974762Snate@binkert.orgdef DebugFlag(name, desc=None):
2984762Snate@binkert.org    if name in debug_flags:
2994762Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3006654Snate@binkert.org    debug_flags[name] = (name, (), desc)
3016654Snate@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')
3115517Snate@binkert.org
3125517Snate@binkert.org########################################################################
3135517Snate@binkert.org#
3145517Snate@binkert.org# Set some compiler variables
3155517Snate@binkert.org#
3165517Snate@binkert.org
3175517Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
3185517Snate@binkert.org# automatically expand '.' to refer to both the source directory and
3196654Snate@binkert.org# the corresponding build directory to pick up generated include
3205517Snate@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
3275517Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3286143Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3296654Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3305517Snate@binkert.org
3315517Snate@binkert.org########################################################################
3325517Snate@binkert.org#
3335517Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
3345517Snate@binkert.org#
3355517Snate@binkert.org
3365517Snate@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:])
3446654Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3456654Snate@binkert.org
3465517Snate@binkert.orgfor extra_dir in extras_dir_list:
3475517Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3486143Snate@binkert.org
3496143Snate@binkert.org    # Also add the corresponding build directory to pick up generated
3506143Snate@binkert.org    # include files.
3516727Ssteve.reinhardt@amd.com    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3525517Snate@binkert.org
3536727Ssteve.reinhardt@amd.com    for root, dirs, files in os.walk(extra_dir, topdown=True):
3545517Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3555517Snate@binkert.org        if 'build' in dirs:
3565517Snate@binkert.org            dirs.remove('build')
3576654Snate@binkert.org
3586654Snate@binkert.org        if 'SConscript' in files:
3597673Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3606654Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3616654Snate@binkert.org
3626654Snate@binkert.orgfor opt in export_vars:
3636654Snate@binkert.org    env.ConfigFile(opt)
3645517Snate@binkert.org
3655517Snate@binkert.orgdef makeTheISA(source, target, env):
3665517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
3676143Snate@binkert.org    target_isa = env['TARGET_ISA']
3685517Snate@binkert.org    def define(isa):
3694762Snate@binkert.org        return isa.upper() + '_ISA'
3705517Snate@binkert.org    
3715517Snate@binkert.org    def namespace(isa):
3726143Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA' 
3736143Snate@binkert.org
3745517Snate@binkert.org
3755517Snate@binkert.org    code = code_formatter()
3765517Snate@binkert.org    code('''\
3775517Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3785517Snate@binkert.org#define __CONFIG_THE_ISA_HH__
3795517Snate@binkert.org
3805517Snate@binkert.org''')
3815517Snate@binkert.org
3825517Snate@binkert.org    for i,isa in enumerate(isas):
3835517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
3846143Snate@binkert.org
3855517Snate@binkert.org    code('''
3866654Snate@binkert.org
3876654Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
3886654Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
3896654Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
3906654Snate@binkert.org
3916654Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
3925517Snate@binkert.org
3935517Snate@binkert.org    code.write(str(target[0]))
3945517Snate@binkert.org
3955517Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
3965517Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
3974762Snate@binkert.org
3984762Snate@binkert.org########################################################################
3994762Snate@binkert.org#
4004762Snate@binkert.org# Prevent any SimObjects from being added after this point, they
4014762Snate@binkert.org# should all have been added in the SConscripts above
4024762Snate@binkert.org#
4037675Snate@binkert.orgSimObject.fixed = True
4044762Snate@binkert.org
4054762Snate@binkert.orgclass DictImporter(object):
4064762Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4074762Snate@binkert.org    map to arbitrary filenames.'''
4084382Sbinkertn@umich.edu    def __init__(self, modules):
4094382Sbinkertn@umich.edu        self.modules = modules
4105517Snate@binkert.org        self.installed = set()
4116654Snate@binkert.org
4125517Snate@binkert.org    def __del__(self):
4135798Snate@binkert.org        self.unload()
4146654Snate@binkert.org
4157673Snate@binkert.org    def unload(self):
4166654Snate@binkert.org        import sys
4176654Snate@binkert.org        for module in self.installed:
4186654Snate@binkert.org            del sys.modules[module]
4196654Snate@binkert.org        self.installed = set()
4206654Snate@binkert.org
4216654Snate@binkert.org    def find_module(self, fullname, path):
4226654Snate@binkert.org        if fullname == 'm5.defines':
4236654Snate@binkert.org            return self
4246669Snate@binkert.org
4256669Snate@binkert.org        if fullname == 'm5.objects':
4266669Snate@binkert.org            return self
4276669Snate@binkert.org
4286669Snate@binkert.org        if fullname.startswith('m5.internal'):
4296669Snate@binkert.org            return None
4306654Snate@binkert.org
4317673Snate@binkert.org        source = self.modules.get(fullname, None)
4325517Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
4335863Snate@binkert.org            return self
4345798Snate@binkert.org
4357756SAli.Saidi@ARM.com        return None
4367816Ssteve.reinhardt@amd.com
4375798Snate@binkert.org    def load_module(self, fullname):
4385798Snate@binkert.org        mod = imp.new_module(fullname)
4395517Snate@binkert.org        sys.modules[fullname] = mod
4405517Snate@binkert.org        self.installed.add(fullname)
4417673Snate@binkert.org
4425517Snate@binkert.org        mod.__loader__ = self
4435517Snate@binkert.org        if fullname == 'm5.objects':
4447673Snate@binkert.org            mod.__path__ = fullname.split('.')
4457673Snate@binkert.org            return mod
4465517Snate@binkert.org
4475798Snate@binkert.org        if fullname == 'm5.defines':
4485798Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
4497974Sgblack@eecs.umich.edu            return mod
4507816Ssteve.reinhardt@amd.com
4515798Snate@binkert.org        source = self.modules[fullname]
4525798Snate@binkert.org        if source.modname == '__init__':
4534762Snate@binkert.org            mod.__path__ = source.modpath
4544762Snate@binkert.org        mod.__file__ = source.abspath
4554762Snate@binkert.org
4564762Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
4574762Snate@binkert.org
4585517Snate@binkert.org        return mod
4595517Snate@binkert.org
4605517Snate@binkert.orgimport m5.SimObject
4615517Snate@binkert.orgimport m5.params
4625517Snate@binkert.orgfrom m5.util import code_formatter
4635517Snate@binkert.org
4647673Snate@binkert.orgm5.SimObject.clear()
4657673Snate@binkert.orgm5.params.clear()
4667673Snate@binkert.org
4675517Snate@binkert.org# install the python importer so we can grab stuff from the source
4685517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
4695517Snate@binkert.org# else we won't know about them for the rest of the stuff.
4705517Snate@binkert.orgimporter = DictImporter(PySource.modules)
4715517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
4725517Snate@binkert.org
4735517Snate@binkert.org# import all sim objects so we can populate the all_objects list
4747673Snate@binkert.org# make sure that we're working with a list, then let's sort it
4757677Snate@binkert.orgfor modname in SimObject.modnames:
4767673Snate@binkert.org    exec('from m5.objects import %s' % modname)
4777673Snate@binkert.org
4785517Snate@binkert.org# we need to unload all of the currently imported modules so that they
4795517Snate@binkert.org# will be re-imported the next time the sconscript is run
4805517Snate@binkert.orgimporter.unload()
4815517Snate@binkert.orgsys.meta_path.remove(importer)
4825517Snate@binkert.org
4835517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
4845517Snate@binkert.orgall_enums = m5.params.allEnums
4857673Snate@binkert.org
4867673Snate@binkert.orgif m5.SimObject.noCxxHeader:
4877673Snate@binkert.org    print >> sys.stderr, \
4885517Snate@binkert.org        "warning: At least one SimObject lacks a header specification. " \
4895517Snate@binkert.org        "This can cause unexpected results in the generated SWIG " \
4905517Snate@binkert.org        "wrappers."
4915517Snate@binkert.org
4925517Snate@binkert.org# Find param types that need to be explicitly wrapped with swig.
4935517Snate@binkert.org# These will be recognized because the ParamDesc will have a
4945517Snate@binkert.org# swig_decl() method.  Most param types are based on types that don't
4957673Snate@binkert.org# need this, either because they're based on native types (like Int)
4967673Snate@binkert.org# or because they're SimObjects (which get swigged independently).
4977673Snate@binkert.org# For now the only things handled here are VectorParam types.
4985517Snate@binkert.orgparams_to_swig = {}
4997675Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
5007675Snate@binkert.org    for param in obj._params.local.values():
5017675Snate@binkert.org        # load the ptype attribute now because it depends on the
5027675Snate@binkert.org        # current version of SimObject.allClasses, but when scons
5037675Snate@binkert.org        # actually uses the value, all versions of
5047675Snate@binkert.org        # SimObject.allClasses will have been loaded
5057675Snate@binkert.org        param.ptype
5067675Snate@binkert.org
5077677Snate@binkert.org        if not hasattr(param, 'swig_decl'):
5087675Snate@binkert.org            continue
5097675Snate@binkert.org        pname = param.ptype_str
5107675Snate@binkert.org        if pname not in params_to_swig:
5117675Snate@binkert.org            params_to_swig[pname] = param
5127675Snate@binkert.org
5137675Snate@binkert.org########################################################################
5147675Snate@binkert.org#
5157675Snate@binkert.org# calculate extra dependencies
5167675Snate@binkert.org#
5174762Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5184762Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
5196143Snate@binkert.org
5206143Snate@binkert.org########################################################################
5216143Snate@binkert.org#
5224762Snate@binkert.org# Commands for the basic automatically generated python files
5234762Snate@binkert.org#
5244762Snate@binkert.org
5257756SAli.Saidi@ARM.com# Generate Python file containing a dict specifying the current
5267816Ssteve.reinhardt@amd.com# buildEnv flags.
5274762Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
5284762Snate@binkert.org    build_env = source[0].get_contents()
5294762Snate@binkert.org
5305463Snate@binkert.org    code = code_formatter()
5315517Snate@binkert.org    code("""
5327677Snate@binkert.orgimport m5.internal
5335463Snate@binkert.orgimport m5.util
5347756SAli.Saidi@ARM.com
5357816Ssteve.reinhardt@amd.combuildEnv = m5.util.SmartDict($build_env)
5364762Snate@binkert.org
5377677Snate@binkert.orgcompileDate = m5.internal.core.compileDate
5384762Snate@binkert.org_globals = globals()
5394762Snate@binkert.orgfor key,val in m5.internal.core.__dict__.iteritems():
5406143Snate@binkert.org    if key.startswith('flag_'):
5416143Snate@binkert.org        flag = key[5:]
5426143Snate@binkert.org        _globals[flag] = val
5434762Snate@binkert.orgdel _globals
5444762Snate@binkert.org""")
5457756SAli.Saidi@ARM.com    code.write(target[0].abspath)
5467816Ssteve.reinhardt@amd.com
5474762Snate@binkert.orgdefines_info = Value(build_env)
5484762Snate@binkert.org# Generate a file with all of the compile options in it
5494762Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
5504762Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
5517756SAli.Saidi@ARM.comPySource('m5', 'python/m5/defines.py')
5527816Ssteve.reinhardt@amd.com
5534762Snate@binkert.org# Generate python file containing info about the M5 source code
5544762Snate@binkert.orgdef makeInfoPyFile(target, source, env):
5557677Snate@binkert.org    code = code_formatter()
5567756SAli.Saidi@ARM.com    for src in source:
5577816Ssteve.reinhardt@amd.com        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
5587675Snate@binkert.org        code('$src = ${{repr(data)}}')
5597677Snate@binkert.org    code.write(str(target[0]))
5605517Snate@binkert.org
5617675Snate@binkert.org# Generate a file that wraps the basic top level files
5627675Snate@binkert.orgenv.Command('python/m5/info.py',
5637675Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
5647675Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
5657675Snate@binkert.orgPySource('m5', 'python/m5/info.py')
5667675Snate@binkert.org
5677675Snate@binkert.org########################################################################
5685517Snate@binkert.org#
5697673Snate@binkert.org# Create all of the SimObject param headers and enum headers
5705517Snate@binkert.org#
5717677Snate@binkert.org
5727675Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
5737673Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5747675Snate@binkert.org
5757675Snate@binkert.org    name = str(source[0].get_contents())
5767675Snate@binkert.org    obj = sim_objects[name]
5777673Snate@binkert.org
5787675Snate@binkert.org    code = code_formatter()
5795517Snate@binkert.org    obj.cxx_param_decl(code)
5807675Snate@binkert.org    code.write(target[0].abspath)
5817675Snate@binkert.org
5827673Snate@binkert.orgdef createParamSwigWrapper(target, source, env):
5837675Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5847675Snate@binkert.org
5857677Snate@binkert.org    name = str(source[0].get_contents())
5867675Snate@binkert.org    param = params_to_swig[name]
5877675Snate@binkert.org
5887675Snate@binkert.org    code = code_formatter()
5895517Snate@binkert.org    param.swig_decl(code)
5907675Snate@binkert.org    code.write(target[0].abspath)
5915517Snate@binkert.org
5927673Snate@binkert.orgdef createEnumStrings(target, source, env):
5935517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5947675Snate@binkert.org
5957677Snate@binkert.org    name = str(source[0].get_contents())
5967756SAli.Saidi@ARM.com    obj = all_enums[name]
5977816Ssteve.reinhardt@amd.com
5987675Snate@binkert.org    code = code_formatter()
5997677Snate@binkert.org    obj.cxx_def(code)
6004762Snate@binkert.org    code.write(target[0].abspath)
6017674Snate@binkert.org
6027674Snate@binkert.orgdef createEnumDecls(target, source, env):
6037674Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6047674Snate@binkert.org
6057674Snate@binkert.org    name = str(source[0].get_contents())
6067674Snate@binkert.org    obj = all_enums[name]
6077674Snate@binkert.org
6087674Snate@binkert.org    code = code_formatter()
6097674Snate@binkert.org    obj.cxx_decl(code)
6107674Snate@binkert.org    code.write(target[0].abspath)
6117674Snate@binkert.org
6127674Snate@binkert.orgdef createEnumSwigWrapper(target, source, env):
6137674Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6147674Snate@binkert.org
6157674Snate@binkert.org    name = str(source[0].get_contents())
6164762Snate@binkert.org    obj = all_enums[name]
6176143Snate@binkert.org
6186143Snate@binkert.org    code = code_formatter()
6197756SAli.Saidi@ARM.com    obj.swig_decl(code)
6207816Ssteve.reinhardt@amd.com    code.write(target[0].abspath)
6217674Snate@binkert.org
6227756SAli.Saidi@ARM.comdef createSimObjectSwigWrapper(target, source, env):
6237816Ssteve.reinhardt@amd.com    name = source[0].get_contents()
6247674Snate@binkert.org    obj = sim_objects[name]
6254382Sbinkertn@umich.edu
6266229Snate@binkert.org    code = code_formatter()
6276229Snate@binkert.org    obj.swig_decl(code)
6286229Snate@binkert.org    code.write(target[0].abspath)
6296229Snate@binkert.org
6306229Snate@binkert.org# Generate all of the SimObject param C++ struct header files
6316229Snate@binkert.orgparams_hh_files = []
6326229Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
6336229Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6346229Snate@binkert.org    extra_deps = [ py_source.tnode ]
6356229Snate@binkert.org
6366229Snate@binkert.org    hh_file = File('params/%s.hh' % name)
6376229Snate@binkert.org    params_hh_files.append(hh_file)
6386229Snate@binkert.org    env.Command(hh_file, Value(name),
6396229Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6406229Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
6416229Snate@binkert.org
6426229Snate@binkert.org# Generate any needed param SWIG wrapper files
6436229Snate@binkert.orgparams_i_files = []
6446229Snate@binkert.orgfor name,param in params_to_swig.iteritems():
6456229Snate@binkert.org    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
6466229Snate@binkert.org    params_i_files.append(i_file)
6475192Ssaidi@eecs.umich.edu    env.Command(i_file, Value(name),
6485517Snate@binkert.org                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
6495517Snate@binkert.org    env.Depends(i_file, depends)
6507673Snate@binkert.org    SwigSource('m5.internal', i_file)
6515517Snate@binkert.org
6526229Snate@binkert.org# Generate all enum header files
6535799Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
6547673Snate@binkert.org    py_source = PySource.modules[enum.__module__]
6557673Snate@binkert.org    extra_deps = [ py_source.tnode ]
6565517Snate@binkert.org
6575517Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
6587673Snate@binkert.org    env.Command(cc_file, Value(name),
6597673Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
6607673Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
6617673Snate@binkert.org    Source(cc_file)
6625517Snate@binkert.org
6637673Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
6647673Snate@binkert.org    env.Command(hh_file, Value(name),
6657673Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
6665517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
6675517Snate@binkert.org
6687673Snate@binkert.org    i_file = File('python/m5/internal/enum_%s.i' % name)
6697673Snate@binkert.org    env.Command(i_file, Value(name),
6707673Snate@binkert.org                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
6717673Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
6725517Snate@binkert.org    SwigSource('m5.internal', i_file)
6737673Snate@binkert.org
6747673Snate@binkert.org# Generate SimObject SWIG wrapper files
6755517Snate@binkert.orgfor name,simobj in sim_objects.iteritems():
6767673Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6777673Snate@binkert.org    extra_deps = [ py_source.tnode ]
6785517Snate@binkert.org
6797673Snate@binkert.org    i_file = File('python/m5/internal/param_%s.i' % name)
6805517Snate@binkert.org    env.Command(i_file, Value(name),
6815517Snate@binkert.org                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
6827673Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
6837673Snate@binkert.org    SwigSource('m5.internal', i_file)
6847673Snate@binkert.org
6857673Snate@binkert.org# Generate the main swig init file
6865517Snate@binkert.orgdef makeEmbeddedSwigInit(target, source, env):
6877673Snate@binkert.org    code = code_formatter()
6887673Snate@binkert.org    module = source[0].get_contents()
6897673Snate@binkert.org    code('''\
6905517Snate@binkert.org#include "sim/init.hh"
6917673Snate@binkert.org
6927673Snate@binkert.orgextern "C" {
6937673Snate@binkert.org    void init_${module}();
6945517Snate@binkert.org}
6957673Snate@binkert.org
6965517Snate@binkert.orgEmbeddedSwig embed_swig_${module}(init_${module});
6975517Snate@binkert.org''')
6985517Snate@binkert.org    code.write(str(target[0]))
6995517Snate@binkert.org    
7006229Snate@binkert.org# Build all swig modules
7017673Snate@binkert.orgfor swig in SwigSource.all:
7025517Snate@binkert.org    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
7035517Snate@binkert.org                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
7047673Snate@binkert.org                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
7055517Snate@binkert.org    cc_file = str(swig.tnode)
7065517Snate@binkert.org    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
7075517Snate@binkert.org    env.Command(init_file, Value(swig.module),
7085517Snate@binkert.org                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
7095517Snate@binkert.org    Source(init_file, **swig.guards)
7105517Snate@binkert.org
7115517Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
7125517Snate@binkert.orgif env['HAVE_PROTOBUF']:
7135517Snate@binkert.org    for proto in ProtoBuf.all:
7147673Snate@binkert.org        # Use both the source and header as the target, and the .proto
7155517Snate@binkert.org        # file as the source. When executing the protoc compiler, also
7167673Snate@binkert.org        # specify the proto_path to avoid having the generated files
7175517Snate@binkert.org        # include the path.
7185517Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
7195517Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
7205517Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
7217673Snate@binkert.org                               Transform("PROTOC")))
7225517Snate@binkert.org
7237673Snate@binkert.org        # Add the C++ source file
7245517Snate@binkert.org        Source(proto.cc_file, **proto.guards)
7255517Snate@binkert.orgelif ProtoBuf.all:
7267673Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
7277673Snate@binkert.org    Exit(1)
7285517Snate@binkert.org
7297673Snate@binkert.org#
7307673Snate@binkert.org# Handle debug flags
7315517Snate@binkert.org#
7327673Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
7337673Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
7347673Snate@binkert.org
7357673Snate@binkert.org    val = eval(source[0].get_contents())
7365517Snate@binkert.org    name, compound, desc = val
7375517Snate@binkert.org    compound = list(sorted(compound))
7385517Snate@binkert.org
7397673Snate@binkert.org    code = code_formatter()
7407673Snate@binkert.org
7415517Snate@binkert.org    # file header
7425517Snate@binkert.org    code('''
7437673Snate@binkert.org/*
7447673Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated
7457673Snate@binkert.org */
7467673Snate@binkert.org
7475517Snate@binkert.org#include "base/debug.hh"
7485517Snate@binkert.org''')
7495517Snate@binkert.org
7505517Snate@binkert.org    for flag in compound:
7517673Snate@binkert.org        code('#include "debug/$flag.hh"')
7527673Snate@binkert.org    code()
7535517Snate@binkert.org    code('namespace Debug {')
7547673Snate@binkert.org    code()
7557673Snate@binkert.org
7567673Snate@binkert.org    if not compound:
7577673Snate@binkert.org        code('SimpleFlag $name("$name", "$desc");')
7587673Snate@binkert.org    else:
7595517Snate@binkert.org        code('CompoundFlag $name("$name", "$desc",')
7605517Snate@binkert.org        code.indent()
7615517Snate@binkert.org        last = len(compound) - 1
7627673Snate@binkert.org        for i,flag in enumerate(compound):
7637673Snate@binkert.org            if i != last:
7647673Snate@binkert.org                code('$flag,')
7655517Snate@binkert.org            else:
7665517Snate@binkert.org                code('$flag);')
7677673Snate@binkert.org        code.dedent()
7685517Snate@binkert.org
7697673Snate@binkert.org    code()
7707673Snate@binkert.org    code('} // namespace Debug')
7715517Snate@binkert.org
7727673Snate@binkert.org    code.write(str(target[0]))
7735517Snate@binkert.org
7745517Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
7755517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
7765517Snate@binkert.org
7776229Snate@binkert.org    val = eval(source[0].get_contents())
7787673Snate@binkert.org    name, compound, desc = val
7795517Snate@binkert.org
7805517Snate@binkert.org    code = code_formatter()
7817673Snate@binkert.org
7825517Snate@binkert.org    # file header boilerplate
7835517Snate@binkert.org    code('''\
7845517Snate@binkert.org/*
7855517Snate@binkert.org * DO NOT EDIT THIS FILE!
7865517Snate@binkert.org *
7875517Snate@binkert.org * Automatically generated by SCons
7885517Snate@binkert.org */
7895517Snate@binkert.org
7905517Snate@binkert.org#ifndef __DEBUG_${name}_HH__
7915517Snate@binkert.org#define __DEBUG_${name}_HH__
7925517Snate@binkert.org
7937673Snate@binkert.orgnamespace Debug {
7945517Snate@binkert.org''')
7955517Snate@binkert.org
7965517Snate@binkert.org    if compound:
7977673Snate@binkert.org        code('class CompoundFlag;')
7985517Snate@binkert.org    code('class SimpleFlag;')
7995517Snate@binkert.org
8007673Snate@binkert.org    if compound:
8015517Snate@binkert.org        code('extern CompoundFlag $name;')
8025517Snate@binkert.org        for flag in compound:
8035517Snate@binkert.org            code('extern SimpleFlag $flag;')
8047673Snate@binkert.org    else:
8057673Snate@binkert.org        code('extern SimpleFlag $name;')
8067673Snate@binkert.org
8075517Snate@binkert.org    code('''
8085517Snate@binkert.org}
8097673Snate@binkert.org
8105517Snate@binkert.org#endif // __DEBUG_${name}_HH__
8115517Snate@binkert.org''')
8127673Snate@binkert.org
8135517Snate@binkert.org    code.write(str(target[0]))
8147673Snate@binkert.org
8157673Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
8165517Snate@binkert.org    n, compound, desc = flag
8175517Snate@binkert.org    assert n == name
8185517Snate@binkert.org
8197673Snate@binkert.org    env.Command('debug/%s.hh' % name, Value(flag),
8205517Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
8215517Snate@binkert.org    env.Command('debug/%s.cc' % name, Value(flag),
8225517Snate@binkert.org                MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
8237673Snate@binkert.org    Source('debug/%s.cc' % name)
8247673Snate@binkert.org
8255517Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
8265517Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
8277673Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
8285517Snate@binkert.org# byte code, compress it, and then generate a c++ file that
8295517Snate@binkert.org# inserts the result into an array.
8305517Snate@binkert.orgdef embedPyFile(target, source, env):
8315517Snate@binkert.org    def c_str(string):
8325517Snate@binkert.org        if string is None:
8335517Snate@binkert.org            return "0"
8345517Snate@binkert.org        return '"%s"' % string
8355517Snate@binkert.org
8365517Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
8375517Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
8387811Ssteve.reinhardt@amd.com    as just bytes with a label in the data section'''
8395517Snate@binkert.org
8405517Snate@binkert.org    src = file(str(source[0]), 'r').read()
8417673Snate@binkert.org
8425517Snate@binkert.org    pysource = PySource.tnodes[source[0]]
8437673Snate@binkert.org    compiled = compile(src, pysource.abspath, 'exec')
8445517Snate@binkert.org    marshalled = marshal.dumps(compiled)
8456143Snate@binkert.org    compressed = zlib.compress(marshalled)
8467756SAli.Saidi@ARM.com    data = compressed
8477816Ssteve.reinhardt@amd.com    sym = pysource.symname
8485192Ssaidi@eecs.umich.edu
8495192Ssaidi@eecs.umich.edu    code = code_formatter()
8507756SAli.Saidi@ARM.com    code('''\
8517816Ssteve.reinhardt@amd.com#include "sim/init.hh"
8527756SAli.Saidi@ARM.com
8537816Ssteve.reinhardt@amd.comnamespace {
8545192Ssaidi@eecs.umich.edu
8555192Ssaidi@eecs.umich.educonst uint8_t data_${sym}[] = {
8567674Snate@binkert.org''')
8575522Snate@binkert.org    code.indent()
8585522Snate@binkert.org    step = 16
8597674Snate@binkert.org    for i in xrange(0, len(data), step):
8607674Snate@binkert.org        x = array.array('B', data[i:i+step])
8617674Snate@binkert.org        code(''.join('%d,' % d for d in x))
8627674Snate@binkert.org    code.dedent()
8637674Snate@binkert.org    
8647674Snate@binkert.org    code('''};
8657674Snate@binkert.org
8667674Snate@binkert.orgEmbeddedPython embedded_${sym}(
8675522Snate@binkert.org    ${{c_str(pysource.arcname)}},
8685522Snate@binkert.org    ${{c_str(pysource.abspath)}},
8695522Snate@binkert.org    ${{c_str(pysource.modpath)}},
8705517Snate@binkert.org    data_${sym},
8715522Snate@binkert.org    ${{len(data)}},
8725517Snate@binkert.org    ${{len(marshalled)}});
8736143Snate@binkert.org
8746727Ssteve.reinhardt@amd.com} // anonymous namespace
8755522Snate@binkert.org''')
8765522Snate@binkert.org    code.write(str(target[0]))
8775522Snate@binkert.org
8787674Snate@binkert.orgfor source in PySource.all:
8795517Snate@binkert.org    env.Command(source.cpp, source.tnode,
8807673Snate@binkert.org                MakeAction(embedPyFile, Transform("EMBED PY")))
8817673Snate@binkert.org    Source(source.cpp, skip_no_python=True)
8827674Snate@binkert.org
8837673Snate@binkert.org########################################################################
8847674Snate@binkert.org#
8857674Snate@binkert.org# Define binaries.  Each different build type (debug, opt, etc.) gets
8867674Snate@binkert.org# a slightly different build environment.
8877674Snate@binkert.org#
8887674Snate@binkert.org
8897674Snate@binkert.org# List of constructed environments to pass back to SConstruct
8905522Snate@binkert.orgdate_source = Source('base/date.cc', skip_lib=True)
8915522Snate@binkert.org
8927674Snate@binkert.org# Capture this directory for the closure makeEnv, otherwise when it is
8937674Snate@binkert.org# called, it won't know what directory it should use.
8947674Snate@binkert.orgvariant_dir = Dir('.').path
8957674Snate@binkert.orgdef variant(*path):
8967673Snate@binkert.org    return os.path.join(variant_dir, *path)
8977674Snate@binkert.orgdef variantd(*path):
8987674Snate@binkert.org    return variant(*path)+'/'
8997674Snate@binkert.org
9007674Snate@binkert.org# Function to create a new build environment as clone of current
9017674Snate@binkert.org# environment 'env' with modified object suffix and optional stripped
9027674Snate@binkert.org# binary.  Additional keyword arguments are appended to corresponding
9037674Snate@binkert.org# build environment vars.
9047674Snate@binkert.orgdef makeEnv(env, label, objsfx, strip = False, **kwargs):
9057811Ssteve.reinhardt@amd.com    # SCons doesn't know to append a library suffix when there is a '.' in the
9067674Snate@binkert.org    # name.  Use '_' instead.
9077673Snate@binkert.org    libname = variant('gem5_' + label)
9085522Snate@binkert.org    exename = variant('gem5.' + label)
9096143Snate@binkert.org    secondary_exename = variant('m5.' + label)
9107756SAli.Saidi@ARM.com
9117816Ssteve.reinhardt@amd.com    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
9127674Snate@binkert.org    new_env.Label = label
9134382Sbinkertn@umich.edu    new_env.Append(**kwargs)
9144382Sbinkertn@umich.edu
9154382Sbinkertn@umich.edu    swig_env = new_env.Clone()
9164382Sbinkertn@umich.edu
9174382Sbinkertn@umich.edu    # Both gcc and clang have issues with unused labels and values in
9184382Sbinkertn@umich.edu    # the SWIG generated code
9194382Sbinkertn@umich.edu    swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
9204382Sbinkertn@umich.edu
9214382Sbinkertn@umich.edu    # Add additional warnings here that should not be applied to
9224382Sbinkertn@umich.edu    # the SWIG generated code
9236143Snate@binkert.org    new_env.Append(CXXFLAGS='-Wmissing-declarations')
924955SN/A
9252655Sstever@eecs.umich.edu    if env['GCC']:
9262655Sstever@eecs.umich.edu        # Depending on the SWIG version, we also need to supress
9272655Sstever@eecs.umich.edu        # warnings about uninitialized variables and missing field
9282655Sstever@eecs.umich.edu        # initializers.
9292655Sstever@eecs.umich.edu        swig_env.Append(CCFLAGS=['-Wno-uninitialized',
9305601Snate@binkert.org                                 '-Wno-missing-field-initializers',
9315601Snate@binkert.org                                 '-Wno-unused-but-set-variable'])
9325601Snate@binkert.org
9335601Snate@binkert.org        # If gcc supports it, also warn for deletion of derived
9345522Snate@binkert.org        # classes with non-virtual desctructors. For gcc >= 4.7 we
9355863Snate@binkert.org        # also have to disable warnings about the SWIG code having
9365601Snate@binkert.org        # potentially uninitialized variables.
9375601Snate@binkert.org        if compareVersions(env['GCC_VERSION'], '4.7') >= 0:
9385601Snate@binkert.org            new_env.Append(CXXFLAGS='-Wdelete-non-virtual-dtor')
9395863Snate@binkert.org            swig_env.Append(CCFLAGS='-Wno-maybe-uninitialized')
9406143Snate@binkert.org    if env['CLANG']:
9415559Snate@binkert.org        # Always enable the warning for deletion of derived classes
9425559Snate@binkert.org        # with non-virtual destructors
9435559Snate@binkert.org        new_env.Append(CXXFLAGS=['-Wdelete-non-virtual-dtor'])
9445559Snate@binkert.org
9455601Snate@binkert.org        swig_env.Append(CCFLAGS=[
9466143Snate@binkert.org                # Some versions of SWIG can return uninitialized values
9476143Snate@binkert.org                '-Wno-sometimes-uninitialized',
9486143Snate@binkert.org                # Register storage is requested in a lot of places in
9496143Snate@binkert.org                # SWIG-generated code.
9506143Snate@binkert.org                '-Wno-deprecated-register',
9516143Snate@binkert.org                ])
9526143Snate@binkert.org
9536143Snate@binkert.org    werror_env = new_env.Clone()
9546143Snate@binkert.org    werror_env.Append(CCFLAGS='-Werror')
9556143Snate@binkert.org
9566143Snate@binkert.org    def make_obj(source, static, extra_deps = None):
9576143Snate@binkert.org        '''This function adds the specified source to the correct
9586143Snate@binkert.org        build environment, and returns the corresponding SCons Object
9596143Snate@binkert.org        nodes'''
9606143Snate@binkert.org
9616143Snate@binkert.org        if source.swig:
9626143Snate@binkert.org            env = swig_env
9636143Snate@binkert.org        elif source.Werror:
9646143Snate@binkert.org            env = werror_env
9656143Snate@binkert.org        else:
9666143Snate@binkert.org            env = new_env
9676143Snate@binkert.org
9686143Snate@binkert.org        if static:
9696143Snate@binkert.org            obj = env.StaticObject(source.tnode)
9706143Snate@binkert.org        else:
9716143Snate@binkert.org            obj = env.SharedObject(source.tnode)
9726143Snate@binkert.org
9736143Snate@binkert.org        if extra_deps:
9746143Snate@binkert.org            env.Depends(obj, extra_deps)
9756143Snate@binkert.org
9766143Snate@binkert.org        return obj
9776143Snate@binkert.org
9786240Snate@binkert.org    lib_guards = {'main': False, 'skip_lib': False}
9795554Snate@binkert.org
9805522Snate@binkert.org    # Without Python, leave out all SWIG and Python content from the
9815522Snate@binkert.org    # library builds.  The option doesn't affect gem5 built as a program
9825797Snate@binkert.org    if GetOption('without_python'):
9835797Snate@binkert.org        lib_guards['skip_no_python'] = False
9845522Snate@binkert.org
9855584Snate@binkert.org    static_objs = [ make_obj(s, True) for s in Source.get(**lib_guards) ]
9866143Snate@binkert.org    shared_objs = [ make_obj(s, False) for s in Source.get(**lib_guards) ]
9875862Snate@binkert.org
9885584Snate@binkert.org    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
9895601Snate@binkert.org    static_objs.append(static_date)
9906143Snate@binkert.org
9916143Snate@binkert.org    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
9922655Sstever@eecs.umich.edu    shared_objs.append(shared_date)
9936143Snate@binkert.org
9946143Snate@binkert.org    # First make a library of everything but main() so other programs can
9956143Snate@binkert.org    # link against m5.
9966143Snate@binkert.org    static_lib = new_env.StaticLibrary(libname, static_objs)
9976143Snate@binkert.org    shared_lib = new_env.SharedLibrary(libname, shared_objs)
9984007Ssaidi@eecs.umich.edu
9994596Sbinkertn@umich.edu    # Now link a stub with main() and the static library.
10004007Ssaidi@eecs.umich.edu    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
10014596Sbinkertn@umich.edu
10027756SAli.Saidi@ARM.com    for test in UnitTest.all:
10037816Ssteve.reinhardt@amd.com        flags = { test.target : True }
10045522Snate@binkert.org        test_sources = Source.get(**flags)
10055601Snate@binkert.org        test_objs = [ make_obj(s, static=True) for s in test_sources ]
10065601Snate@binkert.org        if test.main:
10072655Sstever@eecs.umich.edu            test_objs += main_objs
1008955SN/A        path = variant('unittest/%s.%s' % (test.target, label))
10093918Ssaidi@eecs.umich.edu        new_env.Program(path, test_objs + static_objs)
10103918Ssaidi@eecs.umich.edu
10113918Ssaidi@eecs.umich.edu    progname = exename
10123918Ssaidi@eecs.umich.edu    if strip:
10133918Ssaidi@eecs.umich.edu        progname += '.unstripped'
10143918Ssaidi@eecs.umich.edu
10153918Ssaidi@eecs.umich.edu    targets = new_env.Program(progname, main_objs + static_objs)
10163918Ssaidi@eecs.umich.edu
10173918Ssaidi@eecs.umich.edu    if strip:
10183918Ssaidi@eecs.umich.edu        if sys.platform == 'sunos5':
10193918Ssaidi@eecs.umich.edu            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
10203918Ssaidi@eecs.umich.edu        else:
10213918Ssaidi@eecs.umich.edu            cmd = 'strip $SOURCE -o $TARGET'
10223918Ssaidi@eecs.umich.edu        targets = new_env.Command(exename, progname,
10233940Ssaidi@eecs.umich.edu                    MakeAction(cmd, Transform("STRIP")))
10243940Ssaidi@eecs.umich.edu
10253940Ssaidi@eecs.umich.edu    new_env.Command(secondary_exename, exename,
10263942Ssaidi@eecs.umich.edu            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
10273940Ssaidi@eecs.umich.edu
10283515Ssaidi@eecs.umich.edu    new_env.M5Binary = targets[0]
10293918Ssaidi@eecs.umich.edu    return new_env
10304762Snate@binkert.org
10313515Ssaidi@eecs.umich.edu# Start out with the compiler flags common to all compilers,
10322655Sstever@eecs.umich.edu# i.e. they all use -g for opt and -g -pg for prof
10333918Ssaidi@eecs.umich.educcflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
10343619Sbinkertn@umich.edu           'perf' : ['-g']}
1035955SN/A
1036955SN/A# Start out with the linker flags common to all linkers, i.e. -pg for
10372655Sstever@eecs.umich.edu# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
10383918Ssaidi@eecs.umich.edu# no-as-needed and as-needed as the binutils linker is too clever and
10393619Sbinkertn@umich.edu# simply doesn't link to the library otherwise.
1040955SN/Aldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1041955SN/A           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
10422655Sstever@eecs.umich.edu
10433918Ssaidi@eecs.umich.edu# For Link Time Optimization, the optimisation flags used to compile
10443619Sbinkertn@umich.edu# individual files are decoupled from those used at link time
1045955SN/A# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1046955SN/A# to also update the linker flags based on the target.
10472655Sstever@eecs.umich.eduif env['GCC']:
10483918Ssaidi@eecs.umich.edu    if sys.platform == 'sunos5':
10493683Sstever@eecs.umich.edu        ccflags['debug'] += ['-gstabs+']
10502655Sstever@eecs.umich.edu    else:
10511869SN/A        ccflags['debug'] += ['-ggdb3']
10521869SN/A    ldflags['debug'] += ['-O0']
1053    # opt, fast, prof and perf all share the same cc flags, also add
1054    # the optimization to the ldflags as LTO defers the optimization
1055    # to link time
1056    for target in ['opt', 'fast', 'prof', 'perf']:
1057        ccflags[target] += ['-O3']
1058        ldflags[target] += ['-O3']
1059
1060    ccflags['fast'] += env['LTO_CCFLAGS']
1061    ldflags['fast'] += env['LTO_LDFLAGS']
1062elif env['CLANG']:
1063    ccflags['debug'] += ['-g', '-O0']
1064    # opt, fast, prof and perf all share the same cc flags
1065    for target in ['opt', 'fast', 'prof', 'perf']:
1066        ccflags[target] += ['-O3']
1067else:
1068    print 'Unknown compiler, please fix compiler options'
1069    Exit(1)
1070
1071
1072# To speed things up, we only instantiate the build environments we
1073# need.  We try to identify the needed environment for each target; if
1074# we can't, we fall back on instantiating all the environments just to
1075# be safe.
1076target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1077obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1078              'gpo' : 'perf'}
1079
1080def identifyTarget(t):
1081    ext = t.split('.')[-1]
1082    if ext in target_types:
1083        return ext
1084    if obj2target.has_key(ext):
1085        return obj2target[ext]
1086    match = re.search(r'/tests/([^/]+)/', t)
1087    if match and match.group(1) in target_types:
1088        return match.group(1)
1089    return 'all'
1090
1091needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1092if 'all' in needed_envs:
1093    needed_envs += target_types
1094
1095gem5_root = Dir('.').up().up().abspath
1096def makeEnvirons(target, source, env):
1097    # cause any later Source() calls to be fatal, as a diagnostic.
1098    Source.done()
1099
1100    envList = []
1101
1102    # Debug binary
1103    if 'debug' in needed_envs:
1104        envList.append(
1105            makeEnv(env, 'debug', '.do',
1106                    CCFLAGS = Split(ccflags['debug']),
1107                    CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1108                    LINKFLAGS = Split(ldflags['debug'])))
1109
1110    # Optimized binary
1111    if 'opt' in needed_envs:
1112        envList.append(
1113            makeEnv(env, 'opt', '.o',
1114                    CCFLAGS = Split(ccflags['opt']),
1115                    CPPDEFINES = ['TRACING_ON=1'],
1116                    LINKFLAGS = Split(ldflags['opt'])))
1117
1118    # "Fast" binary
1119    if 'fast' in needed_envs:
1120        envList.append(
1121            makeEnv(env, 'fast', '.fo', strip = True,
1122                    CCFLAGS = Split(ccflags['fast']),
1123                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1124                    LINKFLAGS = Split(ldflags['fast'])))
1125
1126    # Profiled binary using gprof
1127    if 'prof' in needed_envs:
1128        envList.append(
1129            makeEnv(env, 'prof', '.po',
1130                    CCFLAGS = Split(ccflags['prof']),
1131                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1132                    LINKFLAGS = Split(ldflags['prof'])))
1133
1134    # Profiled binary using google-pprof
1135    if 'perf' in needed_envs:
1136        envList.append(
1137            makeEnv(env, 'perf', '.gpo',
1138                    CCFLAGS = Split(ccflags['perf']),
1139                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1140                    LINKFLAGS = Split(ldflags['perf'])))
1141
1142    # Set up the regression tests for each build.
1143    for e in envList:
1144        SConscript(os.path.join(gem5_root, 'tests', 'SConscript'),
1145                   variant_dir = variantd('tests', e.Label),
1146                   exports = { 'env' : e }, duplicate = False)
1147
1148# The MakeEnvirons Builder defers the full dependency collection until
1149# after processing the ISA definition (due to dynamically generated
1150# source files).  Add this dependency to all targets so they will wait
1151# until the environments are completely set up.  Otherwise, a second
1152# process (e.g. -j2 or higher) will try to compile the requested target,
1153# not know how, and fail.
1154env.Append(BUILDERS = {'MakeEnvirons' :
1155                        Builder(action=MakeAction(makeEnvirons,
1156                                                  Transform("ENVIRONS", 1)))})
1157
1158isa_target = env['PHONY_BASE'] + '-deps'
1159environs   = env['PHONY_BASE'] + '-environs'
1160env.Depends('#all-deps',     isa_target)
1161env.Depends('#all-environs', environs)
1162env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1163envSetup = env.MakeEnvirons(environs, isa_target)
1164
1165# make sure no -deps targets occur before all ISAs are complete
1166env.Depends(isa_target, '#all-isas')
1167# likewise for -environs targets and all the -deps targets
1168env.Depends(environs, '#all-deps')
1169