SConscript revision 6727
12137SN/A# -*- mode:python -*-
25268Sksewell@umich.edu
35254Sksewell@umich.edu# Copyright (c) 2004-2005 The Regents of The University of Michigan
45254Sksewell@umich.edu# All rights reserved.
52137SN/A#
65254Sksewell@umich.edu# Redistribution and use in source and binary forms, with or without
75254Sksewell@umich.edu# modification, are permitted provided that the following conditions are
85254Sksewell@umich.edu# met: redistributions of source code must retain the above copyright
95254Sksewell@umich.edu# notice, this list of conditions and the following disclaimer;
105254Sksewell@umich.edu# redistributions in binary form must reproduce the above copyright
115254Sksewell@umich.edu# notice, this list of conditions and the following disclaimer in the
125254Sksewell@umich.edu# documentation and/or other materials provided with the distribution;
135254Sksewell@umich.edu# neither the name of the copyright holders nor the names of its
145254Sksewell@umich.edu# contributors may be used to endorse or promote products derived from
155254Sksewell@umich.edu# this software without specific prior written permission.
162137SN/A#
175254Sksewell@umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
185254Sksewell@umich.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
195254Sksewell@umich.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
205254Sksewell@umich.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
215254Sksewell@umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
225254Sksewell@umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
235254Sksewell@umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
245254Sksewell@umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
255254Sksewell@umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
265254Sksewell@umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
275254Sksewell@umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
295268Sksewell@umich.edu# Authors: Nathan Binkert
305268Sksewell@umich.edu
312137SN/Aimport array
322137SN/Aimport bisect
3311793Sbrandon.potter@amd.comimport imp
3411793Sbrandon.potter@amd.comimport marshal
3511793Sbrandon.potter@amd.comimport os
362597SN/Aimport re
372137SN/Aimport sys
382680Sktlim@umich.eduimport zlib
398232Snate@binkert.org
402137SN/Afrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
418229Snate@binkert.org
422137SN/Aimport SCons
4311794Sbrandon.potter@amd.com
448229Snate@binkert.org# This file defines how to build a particular configuration of M5
454661Sksewell@umich.edu# based on variable settings in the 'env' build environment.
462137SN/A
472137SN/AImport('*')
482137SN/A
492137SN/A# Children need to see the environment
502137SN/AExport('env')
512137SN/A
5211851Sbrandon.potter@amd.combuild_env = [(opt, env[opt]) for opt in export_vars]
532680Sktlim@umich.edu
542137SN/A########################################################################
556701Sgblack@eecs.umich.edu# Code for adding source files of various types
566701Sgblack@eecs.umich.edu#
572137SN/Aclass SourceMeta(type):
582137SN/A    def __init__(cls, name, bases, dict):
599149SAli.Saidi@ARM.com        super(SourceMeta, cls).__init__(name, bases, dict)
609149SAli.Saidi@ARM.com        cls.all = []
612137SN/A        
622137SN/A    def get(cls, **kwargs):
632137SN/A        for src in cls.all:
648706Sandreas.hansson@arm.com            for attr,value in kwargs.iteritems():
652137SN/A                if getattr(src, attr) != value:
662137SN/A                    break
672137SN/A            else:
682484SN/A                yield src
692137SN/A
702137SN/Aclass SourceFile(object):
712137SN/A    __metaclass__ = SourceMeta
7211851Sbrandon.potter@amd.com    def __init__(self, source):
732680Sktlim@umich.edu        tnode = source
742137SN/A        if not isinstance(source, SCons.Node.FS.File):
756701Sgblack@eecs.umich.edu            tnode = File(source)
766701Sgblack@eecs.umich.edu
776701Sgblack@eecs.umich.edu        self.tnode = tnode
786701Sgblack@eecs.umich.edu        self.snode = tnode.srcnode()
792137SN/A        self.filename = str(tnode)
802137SN/A        self.dirname = dirname(self.filename)
816378Sgblack@eecs.umich.edu        self.basename = basename(self.filename)
8211320Ssteve.reinhardt@amd.com        index = self.basename.rfind('.')
836378Sgblack@eecs.umich.edu        if index <= 0:
846701Sgblack@eecs.umich.edu            # dot files aren't extensions
856378Sgblack@eecs.umich.edu            self.extname = self.basename, None
866378Sgblack@eecs.umich.edu        else:
878706Sandreas.hansson@arm.com            self.extname = self.basename[:index], self.basename[index+1:]
886378Sgblack@eecs.umich.edu
896378Sgblack@eecs.umich.edu        for base in type(self).__mro__:
902137SN/A            if issubclass(base, SourceFile):
912484SN/A                bisect.insort_right(base.all, self)       
922137SN/A
932137SN/A    def __lt__(self, other): return self.filename < other.filename
942137SN/A    def __le__(self, other): return self.filename <= other.filename
952137SN/A    def __gt__(self, other): return self.filename > other.filename
962137SN/A    def __ge__(self, other): return self.filename >= other.filename
972137SN/A    def __eq__(self, other): return self.filename == other.filename
982137SN/A    def __ne__(self, other): return self.filename != other.filename
992484SN/A        
1002137SN/Aclass Source(SourceFile):
10111851Sbrandon.potter@amd.com    '''Add a c/c++ source file to the build'''
1022680Sktlim@umich.edu    def __init__(self, source, Werror=True, swig=False, bin_only=False,
1032137SN/A                 skip_lib=False):
1046701Sgblack@eecs.umich.edu        super(Source, self).__init__(source)
1056701Sgblack@eecs.umich.edu
1066701Sgblack@eecs.umich.edu        self.Werror = Werror
1076701Sgblack@eecs.umich.edu        self.swig = swig
1082137SN/A        self.bin_only = bin_only
1092137SN/A        self.skip_lib = bin_only or skip_lib
1102137SN/A
1116378Sgblack@eecs.umich.educlass PySource(SourceFile):
1126378Sgblack@eecs.umich.edu    '''Add a python source file to the named package'''
1136378Sgblack@eecs.umich.edu    invalid_sym_char = re.compile('[^A-z0-9_]')
1146701Sgblack@eecs.umich.edu    modules = {}
1156378Sgblack@eecs.umich.edu    tnodes = {}
1168706Sandreas.hansson@arm.com    symnames = {}
1176378Sgblack@eecs.umich.edu    
1182137SN/A    def __init__(self, package, source):
1196378Sgblack@eecs.umich.edu        super(PySource, self).__init__(source)
1206378Sgblack@eecs.umich.edu
1212137SN/A        modname,ext = self.extname
1222484SN/A        assert ext == 'py'
1232137SN/A
1242137SN/A        if package:
1252137SN/A            path = package.split('.')
1262137SN/A        else:
1272137SN/A            path = []
1282137SN/A
1292137SN/A        modpath = path[:]
1306808Sgblack@eecs.umich.edu        if modname != '__init__':
13111851Sbrandon.potter@amd.com            modpath += [ modname ]
1326808Sgblack@eecs.umich.edu        modpath = '.'.join(modpath)
1336808Sgblack@eecs.umich.edu
1346808Sgblack@eecs.umich.edu        arcpath = path + [ self.basename ]
1356808Sgblack@eecs.umich.edu        abspath = self.snode.abspath
1366808Sgblack@eecs.umich.edu        if not exists(abspath):
1376808Sgblack@eecs.umich.edu            abspath = self.tnode.abspath
1386808Sgblack@eecs.umich.edu
1396808Sgblack@eecs.umich.edu        self.package = package
1402137SN/A        self.modname = modname
1412484SN/A        self.modpath = modpath
1422137SN/A        self.arcname = joinpath(*arcpath)
1432137SN/A        self.abspath = abspath
14413570Sbrandon.potter@amd.com        self.compiled = File(self.filename + 'c')
14513570Sbrandon.potter@amd.com        self.assembly = File(self.filename + '.s')
1462553SN/A        self.symname = "PyEMB_" + PySource.invalid_sym_char.sub('_', modpath)
1472137SN/A
1482484SN/A        PySource.modules[modpath] = self
1492484SN/A        PySource.tnodes[self.tnode] = self
1502137SN/A        PySource.symnames[self.symname] = self
1512137SN/A
1522484SN/Aclass SimObject(PySource):
1532137SN/A    '''Add a SimObject python file as a python source object and add
1542484SN/A    it to a list of sim object modules'''
1552137SN/A
1562553SN/A    fixed = False
1572484SN/A    modnames = []
1585748SSteve.Reinhardt@amd.com
1592484SN/A    def __init__(self, source):
1602137SN/A        super(SimObject, self).__init__('m5.objects', source)
1612484SN/A        if self.fixed:
1622484SN/A            raise AttributeError, "Too late to call SimObject now."
1632137SN/A
1642137SN/A        bisect.insort_right(SimObject.modnames, self.modname)
1652484SN/A
1662484SN/Aclass SwigSource(SourceFile):
1672484SN/A    '''Add a swig file to build'''
1682484SN/A
1692484SN/A    def __init__(self, package, source):
1702484SN/A        super(SwigSource, self).__init__(source)
1712484SN/A
1722484SN/A        modname,ext = self.extname
1732484SN/A        assert ext == 'i'
1742137SN/A
1752484SN/A        self.module = modname
1762484SN/A        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
1772137SN/A        py_file = joinpath(self.dirname, modname + '.py')
1784661Sksewell@umich.edu
1792484SN/A        self.cc_source = Source(cc_file, swig=True)
1805513SMichael.Adler@intel.com        self.py_source = PySource(package, py_file)
1812484SN/A
1822137SN/Aunit_tests = []
1834661Sksewell@umich.edudef UnitTest(target, sources):
1842484SN/A    if not isinstance(sources, (list, tuple)):
1852484SN/A        sources = [ sources ]
1865748SSteve.Reinhardt@amd.com
1872491SN/A    sources = [ Source(src, skip_lib=True) for src in sources ]
1882484SN/A    unit_tests.append((target, sources))
1892484SN/A
1902491SN/A# Children should have access
1912491SN/AExport('Source')
1922137SN/AExport('PySource')
1932484SN/AExport('SimObject')
1942484SN/AExport('SwigSource')
1955867Sksewell@umich.eduExport('UnitTest')
1962686Sksewell@umich.edu
1972484SN/A########################################################################
1982484SN/A#
1992484SN/A# Trace Flags
2002484SN/A#
2015513SMichael.Adler@intel.comtrace_flags = {}
2022137SN/Adef TraceFlag(name, desc=None):
2032484SN/A    if name in trace_flags:
2042484SN/A        raise AttributeError, "Flag %s already specified" % name
2052484SN/A    trace_flags[name] = (name, (), desc)
2062484SN/A
2072484SN/Adef CompoundFlag(name, flags, desc=None):
2082495SN/A    if name in trace_flags:
2092495SN/A        raise AttributeError, "Flag %s already specified" % name
2102484SN/A
2112484SN/A    compound = tuple(flags)
2122495SN/A    trace_flags[name] = (name, compound, desc)
2132484SN/A
2142495SN/AExport('TraceFlag')
2152484SN/AExport('CompoundFlag')
2166378Sgblack@eecs.umich.edu
2176378Sgblack@eecs.umich.edu########################################################################
2184661Sksewell@umich.edu#
2192484SN/A# Set some compiler variables
2202484SN/A#
2212484SN/A
2222484SN/A# Include file paths are rooted in this directory.  SCons will
2232484SN/A# automatically expand '.' to refer to both the source directory and
2242484SN/A# the corresponding build directory to pick up generated include
2252484SN/A# files.
2265513SMichael.Adler@intel.comenv.Append(CPPPATH=Dir('.'))
2272484SN/A
2282484SN/Afor extra_dir in extras_dir_list:
2292484SN/A    env.Append(CPPPATH=Dir(extra_dir))
2302484SN/A
2312553SN/A# Workaround for bug in SCons version > 0.97d20071212
2322495SN/A# Scons bug id: 2006 M5 Bug id: 308 
2332686Sksewell@umich.edufor root, dirs, files in os.walk(base_dir, topdown=True):
2342686Sksewell@umich.edu    Dir(root[len(base_dir) + 1:])
2354661Sksewell@umich.edu
2364661Sksewell@umich.edu########################################################################
2372484SN/A#
2382484SN/A# Walk the tree and execute all SConscripts in subdirectories
2392484SN/A#
2402484SN/A
2412484SN/Ahere = Dir('.').srcnode().abspath
2422484SN/Afor root, dirs, files in os.walk(base_dir, topdown=True):
2432484SN/A    if root == here:
2442484SN/A        # we don't want to recurse back into this SConscript
2452484SN/A        continue
2462484SN/A
2472553SN/A    if 'SConscript' in files:
2482484SN/A        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
2492553SN/A        SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
2502484SN/A
2512484SN/Afor extra_dir in extras_dir_list:
2522484SN/A    prefix_len = len(dirname(extra_dir)) + 1
2532484SN/A    for root, dirs, files in os.walk(extra_dir, topdown=True):
2542484SN/A        if 'SConscript' in files:
2552484SN/A            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
2562484SN/A            SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
2576640Svince@csl.cornell.edu
2582484SN/Afor opt in export_vars:
2592484SN/A    env.ConfigFile(opt)
2602484SN/A
2616378Sgblack@eecs.umich.edudef makeTheISA(source, target, env):
2622484SN/A    f = file(str(target[0]), 'w')
2632492SN/A
2642491SN/A    isas = [ src.get_contents() for src in source ]
2652491SN/A    target = env['TARGET_ISA']
2662495SN/A    def define(isa):
2672484SN/A        return isa.upper() + '_ISA'
2682484SN/A    
2692484SN/A    def namespace(isa):
2702484SN/A        return isa[0].upper() + isa[1:].lower() + 'ISA' 
2712484SN/A
2722484SN/A
2732484SN/A    print >>f, '#ifndef __CONFIG_THE_ISA_HH__'
2742484SN/A    print >>f, '#define __CONFIG_THE_ISA_HH__'
2752484SN/A    print >>f
2762484SN/A    for i,isa in enumerate(isas):
2772484SN/A        print >>f, '#define %s %d' % (define(isa), i + 1)
2782484SN/A    print >>f
2792484SN/A    print >>f, '#define THE_ISA %s' % (define(target))
2802484SN/A    print >>f, '#define TheISA %s' % (namespace(target))
2812484SN/A    print >>f
28210495Snilay@cs.wisc.edu    print >>f, '#endif // __CONFIG_THE_ISA_HH__'  
2832484SN/A
2842484SN/Aenv.Command('config/the_isa.hh', map(Value, all_isa_list), makeTheISA)
2852686Sksewell@umich.edu
2862484SN/A########################################################################
2872553SN/A#
2882484SN/A# Prevent any SimObjects from being added after this point, they
2892484SN/A# should all have been added in the SConscripts above
2902484SN/A#
2912484SN/ASimObject.fixed = True
2922484SN/A
2932484SN/Aclass DictImporter(object):
2944661Sksewell@umich.edu    '''This importer takes a dictionary of arbitrary module names that
2952484SN/A    map to arbitrary filenames.'''
2962484SN/A    def __init__(self, modules):
2972484SN/A        self.modules = modules
2982484SN/A        self.installed = set()
2992484SN/A
3002484SN/A    def __del__(self):
3012484SN/A        self.unload()
3022484SN/A
3032484SN/A    def unload(self):
3042484SN/A        import sys
3052484SN/A        for module in self.installed:
3062484SN/A            del sys.modules[module]
3072484SN/A        self.installed = set()
3085877Shsul@eecs.umich.edu
3092484SN/A    def find_module(self, fullname, path):
3102484SN/A        if fullname == 'm5.defines':
3112484SN/A            return self
3122484SN/A
3132484SN/A        if fullname == 'm5.objects':
3142484SN/A            return self
3152484SN/A
3162484SN/A        if fullname.startswith('m5.internal'):
3172484SN/A            return None
3182484SN/A
3192484SN/A        source = self.modules.get(fullname, None)
3202484SN/A        if source is not None and fullname.startswith('m5.objects'):
3212484SN/A            return self
3222484SN/A
3232137SN/A        return None
3242484SN/A
3252484SN/A    def load_module(self, fullname):
3262484SN/A        mod = imp.new_module(fullname)
3272484SN/A        sys.modules[fullname] = mod
3282484SN/A        self.installed.add(fullname)
3292484SN/A
3302484SN/A        mod.__loader__ = self
3312484SN/A        if fullname == 'm5.objects':
3322484SN/A            mod.__path__ = fullname.split('.')
3332484SN/A            return mod
3342484SN/A
3356378Sgblack@eecs.umich.edu        if fullname == 'm5.defines':
3366378Sgblack@eecs.umich.edu            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
3372484SN/A            return mod
3382484SN/A
3392484SN/A        source = self.modules[fullname]
3406378Sgblack@eecs.umich.edu        if source.modname == '__init__':
3412484SN/A            mod.__path__ = source.modpath
3422484SN/A        mod.__file__ = source.abspath
3432484SN/A
3445513SMichael.Adler@intel.com        exec file(source.abspath, 'r') in mod.__dict__
3452484SN/A
3462484SN/A        return mod
3472484SN/A
3482484SN/Aimport m5.SimObject
3492484SN/Aimport m5.params
3502484SN/A
3512484SN/Am5.SimObject.clear()
3522484SN/Am5.params.clear()
3532484SN/A
3542484SN/A# install the python importer so we can grab stuff from the source
3552553SN/A# tree itself.  We can't have SimObjects added after this point or
3562553SN/A# else we won't know about them for the rest of the stuff.
3572484SN/Aimporter = DictImporter(PySource.modules)
3582484SN/Asys.meta_path[0:0] = [ importer ]
3592484SN/A
36010495Snilay@cs.wisc.edu# import all sim objects so we can populate the all_objects list
3612686Sksewell@umich.edu# make sure that we're working with a list, then let's sort it
3622484SN/Afor modname in SimObject.modnames:
3632484SN/A    exec('from m5.objects import %s' % modname)
3642484SN/A
3652484SN/A# we need to unload all of the currently imported modules so that they
3662484SN/A# will be re-imported the next time the sconscript is run
3672484SN/Aimporter.unload()
3682484SN/Asys.meta_path.remove(importer)
3692484SN/A
3702484SN/Asim_objects = m5.SimObject.allClasses
3712484SN/Aall_enums = m5.params.allEnums
3722484SN/A
3732484SN/Aall_params = {}
3742484SN/Afor name,obj in sorted(sim_objects.iteritems()):
3752484SN/A    for param in obj._params.local.values():
3762484SN/A        # load the ptype attribute now because it depends on the
3772484SN/A        # current version of SimObject.allClasses, but when scons
3782484SN/A        # actually uses the value, all versions of
3792484SN/A        # SimObject.allClasses will have been loaded
3802484SN/A        param.ptype
3812484SN/A
3822484SN/A        if not hasattr(param, 'swig_decl'):
3832484SN/A            continue
3842484SN/A        pname = param.ptype_str
3852484SN/A        if pname not in all_params:
3862484SN/A            all_params[pname] = param
3872495SN/A
3882484SN/A########################################################################
3892484SN/A#
3902484SN/A# calculate extra dependencies
3912484SN/A#
3922484SN/Amodule_depends = ["m5", "m5.SimObject", "m5.params"]
3932484SN/Adepends = [ PySource.modules[dep].tnode for dep in module_depends ]
3942484SN/A
3952484SN/A########################################################################
3962484SN/A#
3972484SN/A# Commands for the basic automatically generated python files
3982484SN/A#
3992484SN/A
4002484SN/A# Generate Python file containing a dict specifying the current
4012484SN/A# buildEnv flags.
4022484SN/Adef makeDefinesPyFile(target, source, env):
4032484SN/A    build_env, hg_info = [ x.get_contents() for x in source ]
4042484SN/A
4052484SN/A    code = m5.util.code_formatter()
4062484SN/A    code("""
4072484SN/Aimport m5.internal
4082484SN/Aimport m5.util
4092484SN/A
4102484SN/AbuildEnv = m5.util.SmartDict($build_env)
4112484SN/AhgRev = '$hg_info'
4122484SN/A
4132484SN/AcompileDate = m5.internal.core.compileDate
4142484SN/A_globals = globals()
4152484SN/Afor key,val in m5.internal.core.__dict__.iteritems():
4162484SN/A    if key.startswith('flag_'):
4172484SN/A        flag = key[5:]
4182484SN/A        _globals[flag] = val
4192484SN/Adel _globals
4202137SN/A""")
4212484SN/A    code.write(str(target[0]))
4222484SN/A
4236805Sgblack@eecs.umich.edudefines_info = [ Value(build_env), Value(env['HG_INFO']) ]
4246808Sgblack@eecs.umich.edu# Generate a file with all of the compile options in it
4256805Sgblack@eecs.umich.eduenv.Command('python/m5/defines.py', defines_info, makeDefinesPyFile)
4266805Sgblack@eecs.umich.eduPySource('m5', 'python/m5/defines.py')
4276805Sgblack@eecs.umich.edu
4286805Sgblack@eecs.umich.edu# Generate python file containing info about the M5 source code
4296805Sgblack@eecs.umich.edudef makeInfoPyFile(target, source, env):
4306805Sgblack@eecs.umich.edu    f = file(str(target[0]), 'w')
4316805Sgblack@eecs.umich.edu    for src in source:
4326805Sgblack@eecs.umich.edu        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
4336805Sgblack@eecs.umich.edu        print >>f, "%s = %s" % (src, repr(data))
4346805Sgblack@eecs.umich.edu    f.close()
4356805Sgblack@eecs.umich.edu
4366805Sgblack@eecs.umich.edu# Generate a file that wraps the basic top level files
4376805Sgblack@eecs.umich.eduenv.Command('python/m5/info.py',
4386805Sgblack@eecs.umich.edu            [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
4396805Sgblack@eecs.umich.edu            makeInfoPyFile)
4406805Sgblack@eecs.umich.eduPySource('m5', 'python/m5/info.py')
4416805Sgblack@eecs.umich.edu
4426805Sgblack@eecs.umich.edu# Generate the __init__.py file for m5.objects
4436805Sgblack@eecs.umich.edudef makeObjectsInitFile(target, source, env):
4446805Sgblack@eecs.umich.edu    f = file(str(target[0]), 'w')
4456805Sgblack@eecs.umich.edu    print >>f, 'from params import *'
4466805Sgblack@eecs.umich.edu    print >>f, 'from m5.SimObject import *'
4476805Sgblack@eecs.umich.edu    for module in source:
4486805Sgblack@eecs.umich.edu        print >>f, 'from %s import *' % module.get_contents()
4496805Sgblack@eecs.umich.edu    f.close()
4506805Sgblack@eecs.umich.edu
4516805Sgblack@eecs.umich.edu# Generate an __init__.py file for the objects package
4526805Sgblack@eecs.umich.eduenv.Command('python/m5/objects/__init__.py',
4536805Sgblack@eecs.umich.edu            map(Value, SimObject.modnames),
4546805Sgblack@eecs.umich.edu            makeObjectsInitFile)
4556805Sgblack@eecs.umich.eduPySource('m5.objects', 'python/m5/objects/__init__.py')
4566805Sgblack@eecs.umich.edu
4576805Sgblack@eecs.umich.edu########################################################################
4586805Sgblack@eecs.umich.edu#
4596805Sgblack@eecs.umich.edu# Create all of the SimObject param headers and enum headers
4606805Sgblack@eecs.umich.edu#
4612137SN/A
4622137SN/Adef createSimObjectParam(target, source, env):
46311851Sbrandon.potter@amd.com    assert len(target) == 1 and len(source) == 1
46411851Sbrandon.potter@amd.com
46511851Sbrandon.potter@amd.com    hh_file = file(target[0].abspath, 'w')
46611851Sbrandon.potter@amd.com    name = str(source[0].get_contents())
4674661Sksewell@umich.edu    obj = sim_objects[name]
4684661Sksewell@umich.edu
4692137SN/A    print >>hh_file, obj.cxx_decl()
4702137SN/A    hh_file.close()
4712137SN/A
4722484SN/Adef createSwigParam(target, source, env):
4732484SN/A    assert len(target) == 1 and len(source) == 1
4742484SN/A
4755981Sstever@gmail.com    i_file = file(target[0].abspath, 'w')
4762137SN/A    name = str(source[0].get_contents())
4772484SN/A    param = all_params[name]
4782484SN/A
4792137SN/A    for line in param.swig_decl():
4804661Sksewell@umich.edu        print >>i_file, line
4814661Sksewell@umich.edu    i_file.close()
4824661Sksewell@umich.edu
4834661Sksewell@umich.edudef createEnumStrings(target, source, env):
4844661Sksewell@umich.edu    assert len(target) == 1 and len(source) == 1
485
486    cc_file = file(target[0].abspath, 'w')
487    name = str(source[0].get_contents())
488    obj = all_enums[name]
489
490    print >>cc_file, obj.cxx_def()
491    cc_file.close()
492
493def createEnumParam(target, source, env):
494    assert len(target) == 1 and len(source) == 1
495
496    hh_file = file(target[0].abspath, 'w')
497    name = str(source[0].get_contents())
498    obj = all_enums[name]
499
500    print >>hh_file, obj.cxx_decl()
501    hh_file.close()
502
503# Generate all of the SimObject param struct header files
504params_hh_files = []
505for name,simobj in sorted(sim_objects.iteritems()):
506    py_source = PySource.modules[simobj.__module__]
507    extra_deps = [ py_source.tnode ]
508
509    hh_file = File('params/%s.hh' % name)
510    params_hh_files.append(hh_file)
511    env.Command(hh_file, Value(name), createSimObjectParam)
512    env.Depends(hh_file, depends + extra_deps)
513
514# Generate any parameter header files needed
515params_i_files = []
516for name,param in all_params.iteritems():
517    i_file = File('params/%s_%s.i' % (name, param.file_ext))
518    params_i_files.append(i_file)
519    env.Command(i_file, Value(name), createSwigParam)
520    env.Depends(i_file, depends)
521
522# Generate all enum header files
523for name,enum in sorted(all_enums.iteritems()):
524    py_source = PySource.modules[enum.__module__]
525    extra_deps = [ py_source.tnode ]
526
527    cc_file = File('enums/%s.cc' % name)
528    env.Command(cc_file, Value(name), createEnumStrings)
529    env.Depends(cc_file, depends + extra_deps)
530    Source(cc_file)
531
532    hh_file = File('enums/%s.hh' % name)
533    env.Command(hh_file, Value(name), createEnumParam)
534    env.Depends(hh_file, depends + extra_deps)
535
536# Build the big monolithic swigged params module (wraps all SimObject
537# param structs and enum structs)
538def buildParams(target, source, env):
539    names = [ s.get_contents() for s in source ]
540    objs = [ sim_objects[name] for name in names ]
541    out = file(target[0].abspath, 'w')
542
543    ordered_objs = []
544    obj_seen = set()
545    def order_obj(obj):
546        name = str(obj)
547        if name in obj_seen:
548            return
549
550        obj_seen.add(name)
551        if str(obj) != 'SimObject':
552            order_obj(obj.__bases__[0])
553
554        ordered_objs.append(obj)
555
556    for obj in objs:
557        order_obj(obj)
558
559    enums = set()
560    predecls = []
561    pd_seen = set()
562
563    def add_pds(*pds):
564        for pd in pds:
565            if pd not in pd_seen:
566                predecls.append(pd)
567                pd_seen.add(pd)
568
569    for obj in ordered_objs:
570        params = obj._params.local.values()
571        for param in params:
572            ptype = param.ptype
573            if issubclass(ptype, m5.params.Enum):
574                if ptype not in enums:
575                    enums.add(ptype)
576            pds = param.swig_predecls()
577            if isinstance(pds, (list, tuple)):
578                add_pds(*pds)
579            else:
580                add_pds(pds)
581
582    print >>out, '%module params'
583
584    print >>out, '%{'
585    for obj in ordered_objs:
586        print >>out, '#include "params/%s.hh"' % obj
587    print >>out, '%}'
588
589    for pd in predecls:
590        print >>out, pd
591
592    enums = list(enums)
593    enums.sort()
594    for enum in enums:
595        print >>out, '%%include "enums/%s.hh"' % enum.__name__
596    print >>out
597
598    for obj in ordered_objs:
599        if obj.swig_objdecls:
600            for decl in obj.swig_objdecls:
601                print >>out, decl
602            continue
603
604        class_path = obj.cxx_class.split('::')
605        classname = class_path[-1]
606        namespaces = class_path[:-1]
607        namespaces.reverse()
608
609        code = ''
610
611        if namespaces:
612            code += '// avoid name conflicts\n'
613            sep_string = '_COLONS_'
614            flat_name = sep_string.join(class_path)
615            code += '%%rename(%s) %s;\n' % (flat_name, classname)
616
617        code += '// stop swig from creating/wrapping default ctor/dtor\n'
618        code += '%%nodefault %s;\n' % classname
619        code += 'class %s ' % classname
620        if obj._base:
621            code += ': public %s' % obj._base.cxx_class
622        code += ' {};\n'
623
624        for ns in namespaces:
625            new_code = 'namespace %s {\n' % ns
626            new_code += code
627            new_code += '}\n'
628            code = new_code
629
630        print >>out, code
631
632    print >>out, '%%include "src/sim/sim_object_params.hh"' % obj
633    for obj in ordered_objs:
634        print >>out, '%%include "params/%s.hh"' % obj
635
636params_file = File('params/params.i')
637names = sorted(sim_objects.keys())
638env.Command(params_file, map(Value, names), buildParams)
639env.Depends(params_file, params_hh_files + params_i_files + depends)
640SwigSource('m5.objects', params_file)
641
642# Build all swig modules
643for swig in SwigSource.all:
644    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
645                '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
646                '-o ${TARGETS[0]} $SOURCES')
647    env.Depends(swig.py_source.tnode, swig.tnode)
648    env.Depends(swig.cc_source.tnode, swig.tnode)
649
650# Generate the main swig init file
651def makeSwigInit(target, source, env):
652    f = file(str(target[0]), 'w')
653    print >>f, 'extern "C" {'
654    for module in source:
655        print >>f, '    void init_%s();' % module.get_contents()
656    print >>f, '}'
657    print >>f, 'void initSwig() {'
658    for module in source:
659        print >>f, '    init_%s();' % module.get_contents()
660    print >>f, '}'
661    f.close()
662
663env.Command('python/swig/init.cc',
664            map(Value, sorted(s.module for s in SwigSource.all)),
665            makeSwigInit)
666Source('python/swig/init.cc')
667
668def getFlags(source_flags):
669    flagsMap = {}
670    flagsList = []
671    for s in source_flags:
672        val = eval(s.get_contents())
673        name, compound, desc = val
674        flagsList.append(val)
675        flagsMap[name] = bool(compound)
676    
677    for name, compound, desc in flagsList:
678        for flag in compound:
679            if flag not in flagsMap:
680                raise AttributeError, "Trace flag %s not found" % flag
681            if flagsMap[flag]:
682                raise AttributeError, \
683                    "Compound flag can't point to another compound flag"
684
685    flagsList.sort()
686    return flagsList
687
688
689# Generate traceflags.py
690def traceFlagsPy(target, source, env):
691    assert(len(target) == 1)
692
693    f = file(str(target[0]), 'w')
694   
695    allFlags = getFlags(source)
696
697    print >>f, 'basic = ['
698    for flag, compound, desc in allFlags:
699        if not compound:
700            print >>f, "    '%s'," % flag
701    print >>f, "    ]"
702    print >>f
703
704    print >>f, 'compound = ['
705    print >>f, "    'All',"
706    for flag, compound, desc in allFlags:
707        if compound:
708            print >>f, "    '%s'," % flag
709    print >>f, "    ]"
710    print >>f
711
712    print >>f, "all = frozenset(basic + compound)"
713    print >>f
714
715    print >>f, 'compoundMap = {'
716    all = tuple([flag for flag,compound,desc in allFlags if not compound])
717    print >>f, "    'All' : %s," % (all, )
718    for flag, compound, desc in allFlags:
719        if compound:
720            print >>f, "    '%s' : %s," % (flag, compound)
721    print >>f, "    }"
722    print >>f
723
724    print >>f, 'descriptions = {'
725    print >>f, "    'All' : 'All flags',"
726    for flag, compound, desc in allFlags:
727        print >>f, "    '%s' : '%s'," % (flag, desc)
728    print >>f, "    }"
729
730    f.close()
731
732def traceFlagsCC(target, source, env):
733    assert(len(target) == 1)
734
735    f = file(str(target[0]), 'w')
736
737    allFlags = getFlags(source)
738
739    # file header
740    print >>f, '''
741/*
742 * DO NOT EDIT THIS FILE! Automatically generated
743 */
744
745#include "base/traceflags.hh"
746
747using namespace Trace;
748
749const char *Trace::flagStrings[] =
750{'''
751
752    # The string array is used by SimpleEnumParam to map the strings
753    # provided by the user to enum values.
754    for flag, compound, desc in allFlags:
755        if not compound:
756            print >>f, '    "%s",' % flag
757
758    print >>f, '    "All",'
759    for flag, compound, desc in allFlags:
760        if compound:
761            print >>f, '    "%s",' % flag
762
763    print >>f, '};'
764    print >>f
765    print >>f, 'const int Trace::numFlagStrings = %d;' % (len(allFlags) + 1)
766    print >>f
767
768    #
769    # Now define the individual compound flag arrays.  There is an array
770    # for each compound flag listing the component base flags.
771    #
772    all = tuple([flag for flag,compound,desc in allFlags if not compound])
773    print >>f, 'static const Flags AllMap[] = {'
774    for flag, compound, desc in allFlags:
775        if not compound:
776            print >>f, "    %s," % flag
777    print >>f, '};'
778    print >>f
779
780    for flag, compound, desc in allFlags:
781        if not compound:
782            continue
783        print >>f, 'static const Flags %sMap[] = {' % flag
784        for flag in compound:
785            print >>f, "    %s," % flag
786        print >>f, "    (Flags)-1"
787        print >>f, '};'
788        print >>f
789
790    #
791    # Finally the compoundFlags[] array maps the compound flags
792    # to their individual arrays/
793    #
794    print >>f, 'const Flags *Trace::compoundFlags[] ='
795    print >>f, '{'
796    print >>f, '    AllMap,'
797    for flag, compound, desc in allFlags:
798        if compound:
799            print >>f, '    %sMap,' % flag
800    # file trailer
801    print >>f, '};'
802
803    f.close()
804
805def traceFlagsHH(target, source, env):
806    assert(len(target) == 1)
807
808    f = file(str(target[0]), 'w')
809
810    allFlags = getFlags(source)
811
812    # file header boilerplate
813    print >>f, '''
814/*
815 * DO NOT EDIT THIS FILE!
816 *
817 * Automatically generated from traceflags.py
818 */
819
820#ifndef __BASE_TRACE_FLAGS_HH__
821#define __BASE_TRACE_FLAGS_HH__
822
823namespace Trace {
824
825enum Flags {'''
826
827    # Generate the enum.  Base flags come first, then compound flags.
828    idx = 0
829    for flag, compound, desc in allFlags:
830        if not compound:
831            print >>f, '    %s = %d,' % (flag, idx)
832            idx += 1
833
834    numBaseFlags = idx
835    print >>f, '    NumFlags = %d,' % idx
836
837    # put a comment in here to separate base from compound flags
838    print >>f, '''
839// The remaining enum values are *not* valid indices for Trace::flags.
840// They are "compound" flags, which correspond to sets of base
841// flags, and are used by changeFlag.'''
842
843    print >>f, '    All = %d,' % idx
844    idx += 1
845    for flag, compound, desc in allFlags:
846        if compound:
847            print >>f, '    %s = %d,' % (flag, idx)
848            idx += 1
849
850    numCompoundFlags = idx - numBaseFlags
851    print >>f, '    NumCompoundFlags = %d' % numCompoundFlags
852
853    # trailer boilerplate
854    print >>f, '''\
855}; // enum Flags
856
857// Array of strings for SimpleEnumParam
858extern const char *flagStrings[];
859extern const int numFlagStrings;
860
861// Array of arraay pointers: for each compound flag, gives the list of
862// base flags to set.  Inidividual flag arrays are terminated by -1.
863extern const Flags *compoundFlags[];
864
865/* namespace Trace */ }
866
867#endif // __BASE_TRACE_FLAGS_HH__
868'''
869
870    f.close()
871
872flags = map(Value, trace_flags.values())
873env.Command('base/traceflags.py', flags, traceFlagsPy)
874PySource('m5', 'base/traceflags.py')
875
876env.Command('base/traceflags.hh', flags, traceFlagsHH)
877env.Command('base/traceflags.cc', flags, traceFlagsCC)
878Source('base/traceflags.cc')
879
880# embed python files.  All .py files that have been indicated by a
881# PySource() call in a SConscript need to be embedded into the M5
882# library.  To do that, we compile the file to byte code, marshal the
883# byte code, compress it, and then generate an assembly file that
884# inserts the result into the data section with symbols indicating the
885# beginning, and end (and with the size at the end)
886def objectifyPyFile(target, source, env):
887    '''Action function to compile a .py into a code object, marshal
888    it, compress it, and stick it into an asm file so the code appears
889    as just bytes with a label in the data section'''
890
891    src = file(str(source[0]), 'r').read()
892    dst = file(str(target[0]), 'w')
893
894    pysource = PySource.tnodes[source[0]]
895    compiled = compile(src, pysource.abspath, 'exec')
896    marshalled = marshal.dumps(compiled)
897    compressed = zlib.compress(marshalled)
898    data = compressed
899
900    # Some C/C++ compilers prepend an underscore to global symbol
901    # names, so if they're going to do that, we need to prepend that
902    # leading underscore to globals in the assembly file.
903    if env['LEADING_UNDERSCORE']:
904        sym = '_' + pysource.symname
905    else:
906        sym = pysource.symname
907
908    step = 16
909    print >>dst, ".data"
910    print >>dst, ".globl %s_beg" % sym
911    print >>dst, ".globl %s_end" % sym
912    print >>dst, "%s_beg:" % sym
913    for i in xrange(0, len(data), step):
914        x = array.array('B', data[i:i+step])
915        print >>dst, ".byte", ','.join([str(d) for d in x])
916    print >>dst, "%s_end:" % sym
917    print >>dst, ".long %d" % len(marshalled)
918
919for source in PySource.all:
920    env.Command(source.assembly, source.tnode, objectifyPyFile)
921    Source(source.assembly)
922
923# Generate init_python.cc which creates a bunch of EmbeddedPyModule
924# structs that describe the embedded python code.  One such struct
925# contains information about the importer that python uses to get at
926# the embedded files, and then there's a list of all of the rest that
927# the importer uses to load the rest on demand.
928def pythonInit(target, source, env):
929    dst = file(str(target[0]), 'w')
930
931    def dump_mod(sym, endchar=','):
932        pysource = PySource.symnames[sym]
933        print >>dst, '    { "%s",' % pysource.arcname
934        print >>dst, '      "%s",' % pysource.modpath
935        print >>dst, '       %s_beg, %s_end,' % (sym, sym)
936        print >>dst, '       %s_end - %s_beg,' % (sym, sym)
937        print >>dst, '       *(int *)%s_end }%s'  % (sym, endchar)
938    
939    print >>dst, '#include "sim/init.hh"'
940
941    for sym in source:
942        sym = sym.get_contents()
943        print >>dst, "extern const char %s_beg[], %s_end[];" % (sym, sym)
944
945    print >>dst, "const EmbeddedPyModule embeddedPyImporter = "
946    dump_mod("PyEMB_importer", endchar=';');
947    print >>dst
948
949    print >>dst, "const EmbeddedPyModule embeddedPyModules[] = {"
950    for i,sym in enumerate(source):
951        sym = sym.get_contents()
952        if sym == "PyEMB_importer":
953            # Skip the importer since we've already exported it
954            continue
955        dump_mod(sym)
956    print >>dst, "    { 0, 0, 0, 0, 0, 0 }"
957    print >>dst, "};"
958
959
960env.Command('sim/init_python.cc',
961            map(Value, (s.symname for s in PySource.all)),
962            pythonInit)
963Source('sim/init_python.cc')
964
965########################################################################
966#
967# Define binaries.  Each different build type (debug, opt, etc.) gets
968# a slightly different build environment.
969#
970
971# List of constructed environments to pass back to SConstruct
972envList = []
973
974date_source = Source('base/date.cc', skip_lib=True)
975
976# Function to create a new build environment as clone of current
977# environment 'env' with modified object suffix and optional stripped
978# binary.  Additional keyword arguments are appended to corresponding
979# build environment vars.
980def makeEnv(label, objsfx, strip = False, **kwargs):
981    # SCons doesn't know to append a library suffix when there is a '.' in the
982    # name.  Use '_' instead.
983    libname = 'm5_' + label
984    exename = 'm5.' + label
985
986    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
987    new_env.Label = label
988    new_env.Append(**kwargs)
989
990    swig_env = new_env.Clone()
991    swig_env.Append(CCFLAGS='-Werror')
992    if env['GCC']:
993        swig_env.Append(CCFLAGS='-Wno-uninitialized')
994        swig_env.Append(CCFLAGS='-Wno-sign-compare')
995        swig_env.Append(CCFLAGS='-Wno-parentheses')
996
997    werror_env = new_env.Clone()
998    werror_env.Append(CCFLAGS='-Werror')
999
1000    def make_obj(source, static, extra_deps = None):
1001        '''This function adds the specified source to the correct
1002        build environment, and returns the corresponding SCons Object
1003        nodes'''
1004
1005        if source.swig:
1006            env = swig_env
1007        elif source.Werror:
1008            env = werror_env
1009        else:
1010            env = new_env
1011
1012        if static:
1013            obj = env.StaticObject(source.tnode)
1014        else:
1015            obj = env.SharedObject(source.tnode)
1016
1017        if extra_deps:
1018            env.Depends(obj, extra_deps)
1019
1020        return obj
1021
1022    static_objs = [ make_obj(s, True) for s in Source.get(skip_lib=False)]
1023    shared_objs = [ make_obj(s, False) for s in Source.get(skip_lib=False)]
1024
1025    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
1026    static_objs.append(static_date)
1027    
1028    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
1029    shared_objs.append(shared_date)
1030
1031    # First make a library of everything but main() so other programs can
1032    # link against m5.
1033    static_lib = new_env.StaticLibrary(libname, static_objs)
1034    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1035
1036    for target, sources in unit_tests:
1037        objs = [ make_obj(s, static=True) for s in sources ]
1038        new_env.Program("unittest/%s.%s" % (target, label), objs + static_objs)
1039
1040    # Now link a stub with main() and the static library.
1041    bin_objs = [make_obj(s, True) for s in Source.get(bin_only=True) ]
1042    progname = exename
1043    if strip:
1044        progname += '.unstripped'
1045
1046    targets = new_env.Program(progname, bin_objs + static_objs)
1047
1048    if strip:
1049        if sys.platform == 'sunos5':
1050            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1051        else:
1052            cmd = 'strip $SOURCE -o $TARGET'
1053        targets = new_env.Command(exename, progname, cmd)
1054            
1055    new_env.M5Binary = targets[0]
1056    envList.append(new_env)
1057
1058# Debug binary
1059ccflags = {}
1060if env['GCC']:
1061    if sys.platform == 'sunos5':
1062        ccflags['debug'] = '-gstabs+'
1063    else:
1064        ccflags['debug'] = '-ggdb3'
1065    ccflags['opt'] = '-g -O3'
1066    ccflags['fast'] = '-O3'
1067    ccflags['prof'] = '-O3 -g -pg'
1068elif env['SUNCC']:
1069    ccflags['debug'] = '-g0'
1070    ccflags['opt'] = '-g -O'
1071    ccflags['fast'] = '-fast'
1072    ccflags['prof'] = '-fast -g -pg'
1073elif env['ICC']:
1074    ccflags['debug'] = '-g -O0'
1075    ccflags['opt'] = '-g -O'
1076    ccflags['fast'] = '-fast'
1077    ccflags['prof'] = '-fast -g -pg'
1078else:
1079    print 'Unknown compiler, please fix compiler options'
1080    Exit(1)
1081
1082makeEnv('debug', '.do',
1083        CCFLAGS = Split(ccflags['debug']),
1084        CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
1085
1086# Optimized binary
1087makeEnv('opt', '.o',
1088        CCFLAGS = Split(ccflags['opt']),
1089        CPPDEFINES = ['TRACING_ON=1'])
1090
1091# "Fast" binary
1092makeEnv('fast', '.fo', strip = True,
1093        CCFLAGS = Split(ccflags['fast']),
1094        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
1095
1096# Profiled binary
1097makeEnv('prof', '.po',
1098        CCFLAGS = Split(ccflags['prof']),
1099        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1100        LINKFLAGS = '-pg')
1101
1102Return('envList')
1103