SConscript revision 6654
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
3711974Sgabeblack@google.comimport sys
38955SN/Aimport zlib
395522Snate@binkert.org
404202Sbinkertn@umich.edufrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
415742Snate@binkert.org
42955SN/Aimport SCons
434381Sbinkertn@umich.edu
444381Sbinkertn@umich.edu# This file defines how to build a particular configuration of M5
458334Snate@binkert.org# based on variable settings in the 'env' build environment.
46955SN/A
47955SN/AImport('*')
484202Sbinkertn@umich.edu
49955SN/A# Children need to see the environment
504382Sbinkertn@umich.eduExport('env')
514382Sbinkertn@umich.edu
524382Sbinkertn@umich.edubuild_env = [(opt, env[opt]) for opt in export_vars]
536654Snate@binkert.org
545517Snate@binkert.org########################################################################
558614Sgblack@eecs.umich.edu# Code for adding source files of various types
567674Snate@binkert.org#
576143Snate@binkert.orgclass SourceMeta(type):
586143Snate@binkert.org    def __init__(cls, name, bases, dict):
596143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
608233Snate@binkert.org        cls.all = []
618233Snate@binkert.org        
628233Snate@binkert.org    def get(cls, **kwargs):
638233Snate@binkert.org        for src in cls.all:
648233Snate@binkert.org            for attr,value in kwargs.iteritems():
658334Snate@binkert.org                if getattr(src, attr) != value:
668334Snate@binkert.org                    break
6710453SAndrew.Bardsley@arm.com            else:
6810453SAndrew.Bardsley@arm.com                yield src
698233Snate@binkert.org
708233Snate@binkert.orgclass SourceFile(object):
718233Snate@binkert.org    __metaclass__ = SourceMeta
728233Snate@binkert.org    def __init__(self, source):
738233Snate@binkert.org        tnode = source
748233Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
7511983Sgabeblack@google.com            tnode = File(source)
7611983Sgabeblack@google.com
7711983Sgabeblack@google.com        self.tnode = tnode
7811983Sgabeblack@google.com        self.snode = tnode.srcnode()
7911983Sgabeblack@google.com        self.filename = str(tnode)
8011983Sgabeblack@google.com        self.dirname = dirname(self.filename)
8111983Sgabeblack@google.com        self.basename = basename(self.filename)
8211983Sgabeblack@google.com        index = self.basename.rfind('.')
8311983Sgabeblack@google.com        if index <= 0:
8411983Sgabeblack@google.com            # dot files aren't extensions
8511983Sgabeblack@google.com            self.extname = self.basename, None
866143Snate@binkert.org        else:
878233Snate@binkert.org            self.extname = self.basename[:index], self.basename[index+1:]
888233Snate@binkert.org
898233Snate@binkert.org        for base in type(self).__mro__:
906143Snate@binkert.org            if issubclass(base, SourceFile):
916143Snate@binkert.org                bisect.insort_right(base.all, self)       
926143Snate@binkert.org
9311308Santhony.gutierrez@amd.com    def __lt__(self, other): return self.filename < other.filename
948233Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
958233Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
968233Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
9711983Sgabeblack@google.com    def __eq__(self, other): return self.filename == other.filename
9811983Sgabeblack@google.com    def __ne__(self, other): return self.filename != other.filename
994762Snate@binkert.org        
1006143Snate@binkert.orgclass Source(SourceFile):
1018233Snate@binkert.org    '''Add a c/c++ source file to the build'''
1028233Snate@binkert.org    def __init__(self, source, Werror=True, swig=False, bin_only=False,
1038233Snate@binkert.org                 skip_lib=False):
1048233Snate@binkert.org        super(Source, self).__init__(source)
1058233Snate@binkert.org
1066143Snate@binkert.org        self.Werror = Werror
1078233Snate@binkert.org        self.swig = swig
1088233Snate@binkert.org        self.bin_only = bin_only
1098233Snate@binkert.org        self.skip_lib = bin_only or skip_lib
1108233Snate@binkert.org
1116143Snate@binkert.orgclass PySource(SourceFile):
1126143Snate@binkert.org    '''Add a python source file to the named package'''
1136143Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
1146143Snate@binkert.org    modules = {}
1156143Snate@binkert.org    tnodes = {}
1166143Snate@binkert.org    symnames = {}
1176143Snate@binkert.org    
1186143Snate@binkert.org    def __init__(self, package, source):
1196143Snate@binkert.org        super(PySource, self).__init__(source)
1207065Snate@binkert.org
1216143Snate@binkert.org        modname,ext = self.extname
1228233Snate@binkert.org        assert ext == 'py'
1238233Snate@binkert.org
1248233Snate@binkert.org        if package:
1258233Snate@binkert.org            path = package.split('.')
1268233Snate@binkert.org        else:
1278233Snate@binkert.org            path = []
1288233Snate@binkert.org
1298233Snate@binkert.org        modpath = path[:]
1308233Snate@binkert.org        if modname != '__init__':
1318233Snate@binkert.org            modpath += [ modname ]
1328233Snate@binkert.org        modpath = '.'.join(modpath)
1338233Snate@binkert.org
1348233Snate@binkert.org        arcpath = path + [ self.basename ]
1358233Snate@binkert.org        debugname = self.snode.abspath
1368233Snate@binkert.org        if not exists(debugname):
1378233Snate@binkert.org            debugname = self.tnode.abspath
1388233Snate@binkert.org
1398233Snate@binkert.org        self.package = package
1408233Snate@binkert.org        self.modname = modname
1418233Snate@binkert.org        self.modpath = modpath
1428233Snate@binkert.org        self.arcname = joinpath(*arcpath)
1438233Snate@binkert.org        self.debugname = debugname
1448233Snate@binkert.org        self.compiled = File(self.filename + 'c')
1458233Snate@binkert.org        self.assembly = File(self.filename + '.s')
1468233Snate@binkert.org        self.symname = "PyEMB_" + PySource.invalid_sym_char.sub('_', modpath)
1478233Snate@binkert.org
1488233Snate@binkert.org        PySource.modules[modpath] = self
1498233Snate@binkert.org        PySource.tnodes[self.tnode] = self
1508233Snate@binkert.org        PySource.symnames[self.symname] = self
1518233Snate@binkert.org
1528233Snate@binkert.orgclass SimObject(PySource):
1536143Snate@binkert.org    '''Add a SimObject python file as a python source object and add
1546143Snate@binkert.org    it to a list of sim object modules'''
1556143Snate@binkert.org
1566143Snate@binkert.org    fixed = False
1576143Snate@binkert.org    modnames = []
1586143Snate@binkert.org
1599982Satgutier@umich.edu    def __init__(self, source):
16010196SCurtis.Dunham@arm.com        super(SimObject, self).__init__('m5.objects', source)
16110196SCurtis.Dunham@arm.com        if self.fixed:
16210196SCurtis.Dunham@arm.com            raise AttributeError, "Too late to call SimObject now."
16310196SCurtis.Dunham@arm.com
16410196SCurtis.Dunham@arm.com        bisect.insort_right(SimObject.modnames, self.modname)
16510196SCurtis.Dunham@arm.com
16610196SCurtis.Dunham@arm.comclass SwigSource(SourceFile):
16710196SCurtis.Dunham@arm.com    '''Add a swig file to build'''
1686143Snate@binkert.org
16911983Sgabeblack@google.com    def __init__(self, package, source):
17011983Sgabeblack@google.com        super(SwigSource, self).__init__(source)
17111983Sgabeblack@google.com
17211983Sgabeblack@google.com        modname,ext = self.extname
17311983Sgabeblack@google.com        assert ext == 'i'
17411983Sgabeblack@google.com
17511983Sgabeblack@google.com        self.module = modname
17611983Sgabeblack@google.com        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
17711983Sgabeblack@google.com        py_file = joinpath(self.dirname, modname + '.py')
1786143Snate@binkert.org
17911988Sandreas.sandberg@arm.com        self.cc_source = Source(cc_file, swig=True)
1808233Snate@binkert.org        self.py_source = PySource(package, py_file)
1818233Snate@binkert.org
1826143Snate@binkert.orgunit_tests = []
1838945Ssteve.reinhardt@amd.comdef UnitTest(target, sources):
1846143Snate@binkert.org    if not isinstance(sources, (list, tuple)):
18511983Sgabeblack@google.com        sources = [ sources ]
18611983Sgabeblack@google.com
1876143Snate@binkert.org    sources = [ Source(src, skip_lib=True) for src in sources ]
1886143Snate@binkert.org    unit_tests.append((target, sources))
1895522Snate@binkert.org
1906143Snate@binkert.org# Children should have access
1916143Snate@binkert.orgExport('Source')
1926143Snate@binkert.orgExport('PySource')
1939982Satgutier@umich.eduExport('SimObject')
1948233Snate@binkert.orgExport('SwigSource')
1958233Snate@binkert.orgExport('UnitTest')
1968233Snate@binkert.org
1976143Snate@binkert.org########################################################################
1986143Snate@binkert.org#
1996143Snate@binkert.org# Trace Flags
2006143Snate@binkert.org#
2015522Snate@binkert.orgtrace_flags = {}
2025522Snate@binkert.orgdef TraceFlag(name, desc=None):
2035522Snate@binkert.org    if name in trace_flags:
2045522Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2055604Snate@binkert.org    trace_flags[name] = (name, (), desc)
2065604Snate@binkert.org
2076143Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
2086143Snate@binkert.org    if name in trace_flags:
2094762Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2104762Snate@binkert.org
2116143Snate@binkert.org    compound = tuple(flags)
2126727Ssteve.reinhardt@amd.com    trace_flags[name] = (name, compound, desc)
2136727Ssteve.reinhardt@amd.com
2146727Ssteve.reinhardt@amd.comExport('TraceFlag')
2154762Snate@binkert.orgExport('CompoundFlag')
2166143Snate@binkert.org
2176143Snate@binkert.org########################################################################
2186143Snate@binkert.org#
2196143Snate@binkert.org# Set some compiler variables
2206727Ssteve.reinhardt@amd.com#
2216143Snate@binkert.org
2227674Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
2237674Snate@binkert.org# automatically expand '.' to refer to both the source directory and
2245604Snate@binkert.org# the corresponding build directory to pick up generated include
2256143Snate@binkert.org# files.
2266143Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
2276143Snate@binkert.org
2284762Snate@binkert.orgfor extra_dir in extras_dir_list:
2296143Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
2304762Snate@binkert.org
2314762Snate@binkert.org# Add a flag defining what THE_ISA should be for all compilation
2324762Snate@binkert.orgenv.Append(CPPDEFINES=[('THE_ISA','%s_ISA' % env['TARGET_ISA'].upper())])
2336143Snate@binkert.org
2346143Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
2354762Snate@binkert.org# Scons bug id: 2006 M5 Bug id: 308 
2368233Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
2378233Snate@binkert.org    Dir(root[len(base_dir) + 1:])
2388233Snate@binkert.org
2398233Snate@binkert.org########################################################################
2406143Snate@binkert.org#
2416143Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
2424762Snate@binkert.org#
2436143Snate@binkert.org
2444762Snate@binkert.orghere = Dir('.').srcnode().abspath
2459396Sandreas.hansson@arm.comfor root, dirs, files in os.walk(base_dir, topdown=True):
2469396Sandreas.hansson@arm.com    if root == here:
2479396Sandreas.hansson@arm.com        # we don't want to recurse back into this SConscript
2489396Sandreas.hansson@arm.com        continue
2499396Sandreas.hansson@arm.com
2509396Sandreas.hansson@arm.com    if 'SConscript' in files:
2519396Sandreas.hansson@arm.com        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
2529396Sandreas.hansson@arm.com        SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
2539396Sandreas.hansson@arm.com
2549396Sandreas.hansson@arm.comfor extra_dir in extras_dir_list:
2559396Sandreas.hansson@arm.com    prefix_len = len(dirname(extra_dir)) + 1
2569396Sandreas.hansson@arm.com    for root, dirs, files in os.walk(extra_dir, topdown=True):
2579396Sandreas.hansson@arm.com        if 'SConscript' in files:
2589930Sandreas.hansson@arm.com            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
2599930Sandreas.hansson@arm.com            SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
2609396Sandreas.hansson@arm.com
2618235Snate@binkert.orgfor opt in export_vars:
2628235Snate@binkert.org    env.ConfigFile(opt)
2636143Snate@binkert.org
2648235Snate@binkert.org########################################################################
2659003SAli.Saidi@ARM.com#
2668235Snate@binkert.org# Prevent any SimObjects from being added after this point, they
2678235Snate@binkert.org# should all have been added in the SConscripts above
2688235Snate@binkert.org#
2698235Snate@binkert.orgSimObject.fixed = True
2708235Snate@binkert.org
2718235Snate@binkert.orgclass DictImporter(object):
2728235Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
2738235Snate@binkert.org    map to arbitrary filenames.'''
2748235Snate@binkert.org    def __init__(self, modules):
2758235Snate@binkert.org        self.modules = modules
2768235Snate@binkert.org        self.installed = set()
2778235Snate@binkert.org
2788235Snate@binkert.org    def __del__(self):
2798235Snate@binkert.org        self.unload()
2809003SAli.Saidi@ARM.com
2818235Snate@binkert.org    def unload(self):
2825584Snate@binkert.org        import sys
2834382Sbinkertn@umich.edu        for module in self.installed:
2844202Sbinkertn@umich.edu            del sys.modules[module]
2854382Sbinkertn@umich.edu        self.installed = set()
2864382Sbinkertn@umich.edu
2879396Sandreas.hansson@arm.com    def find_module(self, fullname, path):
2885584Snate@binkert.org        if fullname == 'm5.defines':
2894382Sbinkertn@umich.edu            return self
2904382Sbinkertn@umich.edu
2914382Sbinkertn@umich.edu        if fullname == 'm5.objects':
2928232Snate@binkert.org            return self
2935192Ssaidi@eecs.umich.edu
2948232Snate@binkert.org        if fullname.startswith('m5.internal'):
2958232Snate@binkert.org            return None
2968232Snate@binkert.org
2975192Ssaidi@eecs.umich.edu        source = self.modules.get(fullname, None)
2988232Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
2995192Ssaidi@eecs.umich.edu            return self
3005799Snate@binkert.org
3018232Snate@binkert.org        return None
3025192Ssaidi@eecs.umich.edu
3035192Ssaidi@eecs.umich.edu    def load_module(self, fullname):
3045192Ssaidi@eecs.umich.edu        mod = imp.new_module(fullname)
3058232Snate@binkert.org        sys.modules[fullname] = mod
3065192Ssaidi@eecs.umich.edu        self.installed.add(fullname)
3078232Snate@binkert.org
3085192Ssaidi@eecs.umich.edu        mod.__loader__ = self
3095192Ssaidi@eecs.umich.edu        if fullname == 'm5.objects':
3105192Ssaidi@eecs.umich.edu            mod.__path__ = fullname.split('.')
3115192Ssaidi@eecs.umich.edu            return mod
3124382Sbinkertn@umich.edu
3134382Sbinkertn@umich.edu        if fullname == 'm5.defines':
3144382Sbinkertn@umich.edu            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
3152667Sstever@eecs.umich.edu            return mod
3162667Sstever@eecs.umich.edu
3172667Sstever@eecs.umich.edu        source = self.modules[fullname]
3182667Sstever@eecs.umich.edu        if source.modname == '__init__':
3192667Sstever@eecs.umich.edu            mod.__path__ = source.modpath
3202667Sstever@eecs.umich.edu        mod.__file__ = source.snode.abspath
3215742Snate@binkert.org
3225742Snate@binkert.org        exec file(source.snode.abspath, 'r') in mod.__dict__
3235742Snate@binkert.org
3245793Snate@binkert.org        return mod
3258334Snate@binkert.org
3265793Snate@binkert.orgimport m5.SimObject
3275793Snate@binkert.orgimport m5.params
3285793Snate@binkert.org
3294382Sbinkertn@umich.edum5.SimObject.clear()
3304762Snate@binkert.orgm5.params.clear()
3315344Sstever@gmail.com
3324382Sbinkertn@umich.edu# install the python importer so we can grab stuff from the source
3335341Sstever@gmail.com# tree itself.  We can't have SimObjects added after this point or
3345742Snate@binkert.org# else we won't know about them for the rest of the stuff.
3355742Snate@binkert.orgimporter = DictImporter(PySource.modules)
3365742Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
3375742Snate@binkert.org
3385742Snate@binkert.org# import all sim objects so we can populate the all_objects list
3394762Snate@binkert.org# make sure that we're working with a list, then let's sort it
3405742Snate@binkert.orgfor modname in SimObject.modnames:
3415742Snate@binkert.org    exec('from m5.objects import %s' % modname)
34211984Sgabeblack@google.com
3437722Sgblack@eecs.umich.edu# we need to unload all of the currently imported modules so that they
3445742Snate@binkert.org# will be re-imported the next time the sconscript is run
3455742Snate@binkert.orgimporter.unload()
3465742Snate@binkert.orgsys.meta_path.remove(importer)
3479930Sandreas.hansson@arm.com
3489930Sandreas.hansson@arm.comsim_objects = m5.SimObject.allClasses
3499930Sandreas.hansson@arm.comall_enums = m5.params.allEnums
3509930Sandreas.hansson@arm.com
3519930Sandreas.hansson@arm.comall_params = {}
3525742Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
3538242Sbradley.danofsky@amd.com    for param in obj._params.local.values():
3548242Sbradley.danofsky@amd.com        # load the ptype attribute now because it depends on the
3558242Sbradley.danofsky@amd.com        # current version of SimObject.allClasses, but when scons
3568242Sbradley.danofsky@amd.com        # actually uses the value, all versions of
3575341Sstever@gmail.com        # SimObject.allClasses will have been loaded
3585742Snate@binkert.org        param.ptype
3597722Sgblack@eecs.umich.edu
3604773Snate@binkert.org        if not hasattr(param, 'swig_decl'):
3616108Snate@binkert.org            continue
3621858SN/A        pname = param.ptype_str
3631085SN/A        if pname not in all_params:
3646658Snate@binkert.org            all_params[pname] = param
3656658Snate@binkert.org
3667673Snate@binkert.org########################################################################
3676658Snate@binkert.org#
3686658Snate@binkert.org# calculate extra dependencies
36911308Santhony.gutierrez@amd.com#
3706658Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
37111308Santhony.gutierrez@amd.comdepends = [ PySource.modules[dep].tnode for dep in module_depends ]
3726658Snate@binkert.org
3736658Snate@binkert.org########################################################################
3747673Snate@binkert.org#
3757673Snate@binkert.org# Commands for the basic automatically generated python files
3767673Snate@binkert.org#
3777673Snate@binkert.org
3787673Snate@binkert.org# Generate Python file containing a dict specifying the current
3797673Snate@binkert.org# buildEnv flags.
3807673Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
38110467Sandreas.hansson@arm.com    build_env, hg_info = [ x.get_contents() for x in source ]
3826658Snate@binkert.org
3837673Snate@binkert.org    code = m5.util.code_formatter()
38410467Sandreas.hansson@arm.com    code("""
38510467Sandreas.hansson@arm.comimport m5.internal
38610467Sandreas.hansson@arm.comimport m5.util
38710467Sandreas.hansson@arm.com
38810467Sandreas.hansson@arm.combuildEnv = m5.util.SmartDict($build_env)
38910467Sandreas.hansson@arm.comhgRev = '$hg_info'
39010467Sandreas.hansson@arm.com
39110467Sandreas.hansson@arm.comcompileDate = m5.internal.core.compileDate
39210467Sandreas.hansson@arm.comfor k,v in m5.internal.core.__dict__.iteritems():
39310467Sandreas.hansson@arm.com    if k.startswith('flag_'):
39410467Sandreas.hansson@arm.com        setattr(buildEnv, k[5:], v)
3957673Snate@binkert.org""")
3967673Snate@binkert.org    code.write(str(target[0]))
3977673Snate@binkert.org
3987673Snate@binkert.orgdefines_info = [ Value(build_env), Value(env['HG_INFO']) ]
3997673Snate@binkert.org# Generate a file with all of the compile options in it
4009048SAli.Saidi@ARM.comenv.Command('python/m5/defines.py', defines_info, makeDefinesPyFile)
4017673Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
4027673Snate@binkert.org
4037673Snate@binkert.org# Generate python file containing info about the M5 source code
4047673Snate@binkert.orgdef makeInfoPyFile(target, source, env):
4056658Snate@binkert.org    f = file(str(target[0]), 'w')
4067756SAli.Saidi@ARM.com    for src in source:
4077816Ssteve.reinhardt@amd.com        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
4086658Snate@binkert.org        print >>f, "%s = %s" % (src, repr(data))
40911308Santhony.gutierrez@amd.com    f.close()
41011308Santhony.gutierrez@amd.com
41111308Santhony.gutierrez@amd.com# Generate a file that wraps the basic top level files
41211308Santhony.gutierrez@amd.comenv.Command('python/m5/info.py',
41311308Santhony.gutierrez@amd.com            [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
41411308Santhony.gutierrez@amd.com            makeInfoPyFile)
41511308Santhony.gutierrez@amd.comPySource('m5', 'python/m5/info.py')
41611308Santhony.gutierrez@amd.com
41711308Santhony.gutierrez@amd.com# Generate the __init__.py file for m5.objects
41811308Santhony.gutierrez@amd.comdef makeObjectsInitFile(target, source, env):
41911308Santhony.gutierrez@amd.com    f = file(str(target[0]), 'w')
42011308Santhony.gutierrez@amd.com    print >>f, 'from params import *'
42111308Santhony.gutierrez@amd.com    print >>f, 'from m5.SimObject import *'
42211308Santhony.gutierrez@amd.com    for module in source:
42311308Santhony.gutierrez@amd.com        print >>f, 'from %s import *' % module.get_contents()
42411308Santhony.gutierrez@amd.com    f.close()
42511308Santhony.gutierrez@amd.com
42611308Santhony.gutierrez@amd.com# Generate an __init__.py file for the objects package
42711308Santhony.gutierrez@amd.comenv.Command('python/m5/objects/__init__.py',
42811308Santhony.gutierrez@amd.com            map(Value, SimObject.modnames),
42911308Santhony.gutierrez@amd.com            makeObjectsInitFile)
43011308Santhony.gutierrez@amd.comPySource('m5.objects', 'python/m5/objects/__init__.py')
43111308Santhony.gutierrez@amd.com
43211308Santhony.gutierrez@amd.com########################################################################
43311308Santhony.gutierrez@amd.com#
43411308Santhony.gutierrez@amd.com# Create all of the SimObject param headers and enum headers
43511308Santhony.gutierrez@amd.com#
43611308Santhony.gutierrez@amd.com
43711308Santhony.gutierrez@amd.comdef createSimObjectParam(target, source, env):
43811308Santhony.gutierrez@amd.com    assert len(target) == 1 and len(source) == 1
43911308Santhony.gutierrez@amd.com
44011308Santhony.gutierrez@amd.com    hh_file = file(target[0].abspath, 'w')
44111308Santhony.gutierrez@amd.com    name = str(source[0].get_contents())
44211308Santhony.gutierrez@amd.com    obj = sim_objects[name]
44311308Santhony.gutierrez@amd.com
44411308Santhony.gutierrez@amd.com    print >>hh_file, obj.cxx_decl()
44511308Santhony.gutierrez@amd.com    hh_file.close()
44611308Santhony.gutierrez@amd.com
44711308Santhony.gutierrez@amd.comdef createSwigParam(target, source, env):
44811308Santhony.gutierrez@amd.com    assert len(target) == 1 and len(source) == 1
44911308Santhony.gutierrez@amd.com
45011308Santhony.gutierrez@amd.com    i_file = file(target[0].abspath, 'w')
45111308Santhony.gutierrez@amd.com    name = str(source[0].get_contents())
45211308Santhony.gutierrez@amd.com    param = all_params[name]
45311308Santhony.gutierrez@amd.com
4544382Sbinkertn@umich.edu    for line in param.swig_decl():
4554382Sbinkertn@umich.edu        print >>i_file, line
4564762Snate@binkert.org    i_file.close()
4574762Snate@binkert.org
4584762Snate@binkert.orgdef createEnumStrings(target, source, env):
4596654Snate@binkert.org    assert len(target) == 1 and len(source) == 1
4606654Snate@binkert.org
4615517Snate@binkert.org    cc_file = file(target[0].abspath, 'w')
4625517Snate@binkert.org    name = str(source[0].get_contents())
4635517Snate@binkert.org    obj = all_enums[name]
4645517Snate@binkert.org
4655517Snate@binkert.org    print >>cc_file, obj.cxx_def()
4665517Snate@binkert.org    cc_file.close()
4675517Snate@binkert.org
4685517Snate@binkert.orgdef createEnumParam(target, source, env):
4695517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
4705517Snate@binkert.org
4715517Snate@binkert.org    hh_file = file(target[0].abspath, 'w')
4725517Snate@binkert.org    name = str(source[0].get_contents())
4735517Snate@binkert.org    obj = all_enums[name]
4745517Snate@binkert.org
4755517Snate@binkert.org    print >>hh_file, obj.cxx_decl()
4765517Snate@binkert.org    hh_file.close()
4775517Snate@binkert.org
4786654Snate@binkert.org# Generate all of the SimObject param struct header files
4795517Snate@binkert.orgparams_hh_files = []
4805517Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
4815517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
4825517Snate@binkert.org    extra_deps = [ py_source.tnode ]
4835517Snate@binkert.org
48411802Sandreas.sandberg@arm.com    hh_file = File('params/%s.hh' % name)
4855517Snate@binkert.org    params_hh_files.append(hh_file)
4865517Snate@binkert.org    env.Command(hh_file, Value(name), createSimObjectParam)
4876143Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
4886654Snate@binkert.org
4895517Snate@binkert.org# Generate any parameter header files needed
4905517Snate@binkert.orgparams_i_files = []
4915517Snate@binkert.orgfor name,param in all_params.iteritems():
4925517Snate@binkert.org    if isinstance(param, m5.params.VectorParamDesc):
4935517Snate@binkert.org        ext = 'vptype'
4945517Snate@binkert.org    else:
4955517Snate@binkert.org        ext = 'ptype'
4965517Snate@binkert.org
4975517Snate@binkert.org    i_file = File('params/%s_%s.i' % (name, ext))
4985517Snate@binkert.org    params_i_files.append(i_file)
4995517Snate@binkert.org    env.Command(i_file, Value(name), createSwigParam)
5005517Snate@binkert.org    env.Depends(i_file, depends)
5015517Snate@binkert.org
5025517Snate@binkert.org# Generate all enum header files
5036654Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
5046654Snate@binkert.org    py_source = PySource.modules[enum.__module__]
5055517Snate@binkert.org    extra_deps = [ py_source.tnode ]
5065517Snate@binkert.org
5076143Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
5086143Snate@binkert.org    env.Command(cc_file, Value(name), createEnumStrings)
5096143Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
5106727Ssteve.reinhardt@amd.com    Source(cc_file)
5115517Snate@binkert.org
5126727Ssteve.reinhardt@amd.com    hh_file = File('enums/%s.hh' % name)
5135517Snate@binkert.org    env.Command(hh_file, Value(name), createEnumParam)
5145517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
5155517Snate@binkert.org
5166654Snate@binkert.org# Build the big monolithic swigged params module (wraps all SimObject
5176654Snate@binkert.org# param structs and enum structs)
5187673Snate@binkert.orgdef buildParams(target, source, env):
5196654Snate@binkert.org    names = [ s.get_contents() for s in source ]
5206654Snate@binkert.org    objs = [ sim_objects[name] for name in names ]
5216654Snate@binkert.org    out = file(target[0].abspath, 'w')
5226654Snate@binkert.org
5235517Snate@binkert.org    ordered_objs = []
5245517Snate@binkert.org    obj_seen = set()
5255517Snate@binkert.org    def order_obj(obj):
5266143Snate@binkert.org        name = str(obj)
5275517Snate@binkert.org        if name in obj_seen:
5284762Snate@binkert.org            return
5295517Snate@binkert.org
5305517Snate@binkert.org        obj_seen.add(name)
5316143Snate@binkert.org        if str(obj) != 'SimObject':
5326143Snate@binkert.org            order_obj(obj.__bases__[0])
5335517Snate@binkert.org
5345517Snate@binkert.org        ordered_objs.append(obj)
5355517Snate@binkert.org
5365517Snate@binkert.org    for obj in objs:
5375517Snate@binkert.org        order_obj(obj)
5385517Snate@binkert.org
5395517Snate@binkert.org    enums = set()
5405517Snate@binkert.org    predecls = []
5415517Snate@binkert.org    pd_seen = set()
5426143Snate@binkert.org
5435517Snate@binkert.org    def add_pds(*pds):
5446654Snate@binkert.org        for pd in pds:
5456654Snate@binkert.org            if pd not in pd_seen:
5466654Snate@binkert.org                predecls.append(pd)
5476654Snate@binkert.org                pd_seen.add(pd)
5486654Snate@binkert.org
5496654Snate@binkert.org    for obj in ordered_objs:
5504762Snate@binkert.org        params = obj._params.local.values()
5514762Snate@binkert.org        for param in params:
5524762Snate@binkert.org            ptype = param.ptype
5534762Snate@binkert.org            if issubclass(ptype, m5.params.Enum):
5544762Snate@binkert.org                if ptype not in enums:
5557675Snate@binkert.org                    enums.add(ptype)
55610584Sandreas.hansson@arm.com            pds = param.swig_predecls()
5574762Snate@binkert.org            if isinstance(pds, (list, tuple)):
5584762Snate@binkert.org                add_pds(*pds)
5594762Snate@binkert.org            else:
5604762Snate@binkert.org                add_pds(pds)
5614382Sbinkertn@umich.edu
5624382Sbinkertn@umich.edu    print >>out, '%module params'
5635517Snate@binkert.org
5646654Snate@binkert.org    print >>out, '%{'
5655517Snate@binkert.org    for obj in ordered_objs:
5668126Sgblack@eecs.umich.edu        print >>out, '#include "params/%s.hh"' % obj
5676654Snate@binkert.org    print >>out, '%}'
5687673Snate@binkert.org
5696654Snate@binkert.org    for pd in predecls:
57011802Sandreas.sandberg@arm.com        print >>out, pd
5716654Snate@binkert.org
5726654Snate@binkert.org    enums = list(enums)
5736654Snate@binkert.org    enums.sort()
5746654Snate@binkert.org    for enum in enums:
57511802Sandreas.sandberg@arm.com        print >>out, '%%include "enums/%s.hh"' % enum.__name__
5766669Snate@binkert.org    print >>out
57711802Sandreas.sandberg@arm.com
5786669Snate@binkert.org    for obj in ordered_objs:
5796669Snate@binkert.org        if obj.swig_objdecls:
5806669Snate@binkert.org            for decl in obj.swig_objdecls:
5816669Snate@binkert.org                print >>out, decl
5826654Snate@binkert.org            continue
5837673Snate@binkert.org
5845517Snate@binkert.org        class_path = obj.cxx_class.split('::')
5858126Sgblack@eecs.umich.edu        classname = class_path[-1]
5865798Snate@binkert.org        namespaces = class_path[:-1]
5877756SAli.Saidi@ARM.com        namespaces.reverse()
5887816Ssteve.reinhardt@amd.com
5895798Snate@binkert.org        code = ''
5905798Snate@binkert.org
5915517Snate@binkert.org        if namespaces:
5925517Snate@binkert.org            code += '// avoid name conflicts\n'
5937673Snate@binkert.org            sep_string = '_COLONS_'
5945517Snate@binkert.org            flat_name = sep_string.join(class_path)
5955517Snate@binkert.org            code += '%%rename(%s) %s;\n' % (flat_name, classname)
5967673Snate@binkert.org
5977673Snate@binkert.org        code += '// stop swig from creating/wrapping default ctor/dtor\n'
5985517Snate@binkert.org        code += '%%nodefault %s;\n' % classname
5995798Snate@binkert.org        code += 'class %s ' % classname
6005798Snate@binkert.org        if obj._base:
6018333Snate@binkert.org            code += ': public %s' % obj._base.cxx_class
6027816Ssteve.reinhardt@amd.com        code += ' {};\n'
6035798Snate@binkert.org
6045798Snate@binkert.org        for ns in namespaces:
6054762Snate@binkert.org            new_code = 'namespace %s {\n' % ns
6064762Snate@binkert.org            new_code += code
6074762Snate@binkert.org            new_code += '}\n'
6084762Snate@binkert.org            code = new_code
6094762Snate@binkert.org
6108596Ssteve.reinhardt@amd.com        print >>out, code
6115517Snate@binkert.org
6125517Snate@binkert.org    print >>out, '%%include "src/sim/sim_object_params.hh"' % obj
61311997Sgabeblack@google.com    for obj in ordered_objs:
6145517Snate@binkert.org        print >>out, '%%include "params/%s.hh"' % obj
6155517Snate@binkert.org
6167673Snate@binkert.orgparams_file = File('params/params.i')
6178596Ssteve.reinhardt@amd.comnames = sorted(sim_objects.keys())
6187673Snate@binkert.orgenv.Command(params_file, map(Value, names), buildParams)
6195517Snate@binkert.orgenv.Depends(params_file, params_hh_files + params_i_files + depends)
62010458Sandreas.hansson@arm.comSwigSource('m5.objects', params_file)
62110458Sandreas.hansson@arm.com
62210458Sandreas.hansson@arm.com# Build all swig modules
62310458Sandreas.hansson@arm.comfor swig in SwigSource.all:
62410458Sandreas.hansson@arm.com    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
62510458Sandreas.hansson@arm.com                '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
62610458Sandreas.hansson@arm.com                '-o ${TARGETS[0]} $SOURCES')
62710458Sandreas.hansson@arm.com    env.Depends(swig.py_source.tnode, swig.tnode)
62810458Sandreas.hansson@arm.com    env.Depends(swig.cc_source.tnode, swig.tnode)
62910458Sandreas.hansson@arm.com
63010458Sandreas.hansson@arm.com# Generate the main swig init file
63110458Sandreas.hansson@arm.comdef makeSwigInit(target, source, env):
6325517Snate@binkert.org    f = file(str(target[0]), 'w')
63311996Sgabeblack@google.com    print >>f, 'extern "C" {'
6345517Snate@binkert.org    for module in source:
63511997Sgabeblack@google.com        print >>f, '    void init_%s();' % module.get_contents()
63611996Sgabeblack@google.com    print >>f, '}'
6375517Snate@binkert.org    print >>f, 'void initSwig() {'
6385517Snate@binkert.org    for module in source:
6397673Snate@binkert.org        print >>f, '    init_%s();' % module.get_contents()
6407673Snate@binkert.org    print >>f, '}'
64111996Sgabeblack@google.com    f.close()
64211988Sandreas.sandberg@arm.com
6437673Snate@binkert.orgenv.Command('python/swig/init.cc',
6445517Snate@binkert.org            map(Value, sorted(s.module for s in SwigSource.all)),
6458596Ssteve.reinhardt@amd.com            makeSwigInit)
6465517Snate@binkert.orgSource('python/swig/init.cc')
6475517Snate@binkert.org
64811997Sgabeblack@google.comdef getFlags(source_flags):
6495517Snate@binkert.org    flagsMap = {}
6505517Snate@binkert.org    flagsList = []
6517673Snate@binkert.org    for s in source_flags:
6527673Snate@binkert.org        val = eval(s.get_contents())
6537673Snate@binkert.org        name, compound, desc = val
6545517Snate@binkert.org        flagsList.append(val)
65511988Sandreas.sandberg@arm.com        flagsMap[name] = bool(compound)
65611997Sgabeblack@google.com    
6578596Ssteve.reinhardt@amd.com    for name, compound, desc in flagsList:
6588596Ssteve.reinhardt@amd.com        for flag in compound:
6598596Ssteve.reinhardt@amd.com            if flag not in flagsMap:
66011988Sandreas.sandberg@arm.com                raise AttributeError, "Trace flag %s not found" % flag
6618596Ssteve.reinhardt@amd.com            if flagsMap[flag]:
6628596Ssteve.reinhardt@amd.com                raise AttributeError, \
6638596Ssteve.reinhardt@amd.com                    "Compound flag can't point to another compound flag"
6644762Snate@binkert.org
6656143Snate@binkert.org    flagsList.sort()
6666143Snate@binkert.org    return flagsList
6676143Snate@binkert.org
6684762Snate@binkert.org
6694762Snate@binkert.org# Generate traceflags.py
6704762Snate@binkert.orgdef traceFlagsPy(target, source, env):
6717756SAli.Saidi@ARM.com    assert(len(target) == 1)
6728596Ssteve.reinhardt@amd.com
6734762Snate@binkert.org    f = file(str(target[0]), 'w')
6744762Snate@binkert.org   
67510458Sandreas.hansson@arm.com    allFlags = getFlags(source)
67610458Sandreas.hansson@arm.com
67710458Sandreas.hansson@arm.com    print >>f, 'basic = ['
67810458Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
67910458Sandreas.hansson@arm.com        if not compound:
68010458Sandreas.hansson@arm.com            print >>f, "    '%s'," % flag
68110458Sandreas.hansson@arm.com    print >>f, "    ]"
68210458Sandreas.hansson@arm.com    print >>f
68310458Sandreas.hansson@arm.com
68410458Sandreas.hansson@arm.com    print >>f, 'compound = ['
68510458Sandreas.hansson@arm.com    print >>f, "    'All',"
68610458Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
68710458Sandreas.hansson@arm.com        if compound:
68810458Sandreas.hansson@arm.com            print >>f, "    '%s'," % flag
68910458Sandreas.hansson@arm.com    print >>f, "    ]"
69010458Sandreas.hansson@arm.com    print >>f
69110458Sandreas.hansson@arm.com
69210458Sandreas.hansson@arm.com    print >>f, "all = frozenset(basic + compound)"
69310458Sandreas.hansson@arm.com    print >>f
69410458Sandreas.hansson@arm.com
69510458Sandreas.hansson@arm.com    print >>f, 'compoundMap = {'
69610458Sandreas.hansson@arm.com    all = tuple([flag for flag,compound,desc in allFlags if not compound])
69710458Sandreas.hansson@arm.com    print >>f, "    'All' : %s," % (all, )
69810458Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
69910458Sandreas.hansson@arm.com        if compound:
70010458Sandreas.hansson@arm.com            print >>f, "    '%s' : %s," % (flag, compound)
70110458Sandreas.hansson@arm.com    print >>f, "    }"
70210458Sandreas.hansson@arm.com    print >>f
70310458Sandreas.hansson@arm.com
70410458Sandreas.hansson@arm.com    print >>f, 'descriptions = {'
70510458Sandreas.hansson@arm.com    print >>f, "    'All' : 'All flags',"
70610458Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
70710458Sandreas.hansson@arm.com        print >>f, "    '%s' : '%s'," % (flag, desc)
70810458Sandreas.hansson@arm.com    print >>f, "    }"
70910458Sandreas.hansson@arm.com
71010458Sandreas.hansson@arm.com    f.close()
71110458Sandreas.hansson@arm.com
71210458Sandreas.hansson@arm.comdef traceFlagsCC(target, source, env):
71310458Sandreas.hansson@arm.com    assert(len(target) == 1)
71410458Sandreas.hansson@arm.com
71510458Sandreas.hansson@arm.com    f = file(str(target[0]), 'w')
71610458Sandreas.hansson@arm.com
71710458Sandreas.hansson@arm.com    allFlags = getFlags(source)
71810458Sandreas.hansson@arm.com
71910458Sandreas.hansson@arm.com    # file header
72010458Sandreas.hansson@arm.com    print >>f, '''
72110458Sandreas.hansson@arm.com/*
72210458Sandreas.hansson@arm.com * DO NOT EDIT THIS FILE! Automatically generated
72310458Sandreas.hansson@arm.com */
72410584Sandreas.hansson@arm.com
72510458Sandreas.hansson@arm.com#include "base/traceflags.hh"
72610458Sandreas.hansson@arm.com
72710458Sandreas.hansson@arm.comusing namespace Trace;
72810458Sandreas.hansson@arm.com
72910458Sandreas.hansson@arm.comconst char *Trace::flagStrings[] =
7304762Snate@binkert.org{'''
7316143Snate@binkert.org
7326143Snate@binkert.org    # The string array is used by SimpleEnumParam to map the strings
7336143Snate@binkert.org    # provided by the user to enum values.
7344762Snate@binkert.org    for flag, compound, desc in allFlags:
7354762Snate@binkert.org        if not compound:
73611996Sgabeblack@google.com            print >>f, '    "%s",' % flag
7377816Ssteve.reinhardt@amd.com
7384762Snate@binkert.org    print >>f, '    "All",'
7394762Snate@binkert.org    for flag, compound, desc in allFlags:
7404762Snate@binkert.org        if compound:
7414762Snate@binkert.org            print >>f, '    "%s",' % flag
7427756SAli.Saidi@ARM.com
7438596Ssteve.reinhardt@amd.com    print >>f, '};'
7444762Snate@binkert.org    print >>f
7454762Snate@binkert.org    print >>f, 'const int Trace::numFlagStrings = %d;' % (len(allFlags) + 1)
74611988Sandreas.sandberg@arm.com    print >>f
74711988Sandreas.sandberg@arm.com
74811988Sandreas.sandberg@arm.com    #
74911988Sandreas.sandberg@arm.com    # Now define the individual compound flag arrays.  There is an array
75011988Sandreas.sandberg@arm.com    # for each compound flag listing the component base flags.
75111988Sandreas.sandberg@arm.com    #
75211988Sandreas.sandberg@arm.com    all = tuple([flag for flag,compound,desc in allFlags if not compound])
75311988Sandreas.sandberg@arm.com    print >>f, 'static const Flags AllMap[] = {'
75411988Sandreas.sandberg@arm.com    for flag, compound, desc in allFlags:
75511988Sandreas.sandberg@arm.com        if not compound:
75611988Sandreas.sandberg@arm.com            print >>f, "    %s," % flag
7574382Sbinkertn@umich.edu    print >>f, '};'
7589396Sandreas.hansson@arm.com    print >>f
7599396Sandreas.hansson@arm.com
7609396Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
7619396Sandreas.hansson@arm.com        if not compound:
7629396Sandreas.hansson@arm.com            continue
7639396Sandreas.hansson@arm.com        print >>f, 'static const Flags %sMap[] = {' % flag
7649396Sandreas.hansson@arm.com        for flag in compound:
7659396Sandreas.hansson@arm.com            print >>f, "    %s," % flag
7669396Sandreas.hansson@arm.com        print >>f, "    (Flags)-1"
7679396Sandreas.hansson@arm.com        print >>f, '};'
7689396Sandreas.hansson@arm.com        print >>f
7699396Sandreas.hansson@arm.com
7709396Sandreas.hansson@arm.com    #
7719396Sandreas.hansson@arm.com    # Finally the compoundFlags[] array maps the compound flags
7729396Sandreas.hansson@arm.com    # to their individual arrays/
7739396Sandreas.hansson@arm.com    #
7749396Sandreas.hansson@arm.com    print >>f, 'const Flags *Trace::compoundFlags[] ='
7759396Sandreas.hansson@arm.com    print >>f, '{'
7768232Snate@binkert.org    print >>f, '    AllMap,'
7778232Snate@binkert.org    for flag, compound, desc in allFlags:
7788232Snate@binkert.org        if compound:
7798232Snate@binkert.org            print >>f, '    %sMap,' % flag
7808232Snate@binkert.org    # file trailer
7816229Snate@binkert.org    print >>f, '};'
78210455SCurtis.Dunham@arm.com
7836229Snate@binkert.org    f.close()
78410455SCurtis.Dunham@arm.com
78510455SCurtis.Dunham@arm.comdef traceFlagsHH(target, source, env):
78610455SCurtis.Dunham@arm.com    assert(len(target) == 1)
7875517Snate@binkert.org
7885517Snate@binkert.org    f = file(str(target[0]), 'w')
7897673Snate@binkert.org
7905517Snate@binkert.org    allFlags = getFlags(source)
79110455SCurtis.Dunham@arm.com
7925517Snate@binkert.org    # file header boilerplate
7935517Snate@binkert.org    print >>f, '''
7948232Snate@binkert.org/*
79510455SCurtis.Dunham@arm.com * DO NOT EDIT THIS FILE!
79610455SCurtis.Dunham@arm.com *
79710455SCurtis.Dunham@arm.com * Automatically generated from traceflags.py
7987673Snate@binkert.org */
7997673Snate@binkert.org
80010455SCurtis.Dunham@arm.com#ifndef __BASE_TRACE_FLAGS_HH__
80110455SCurtis.Dunham@arm.com#define __BASE_TRACE_FLAGS_HH__
80210455SCurtis.Dunham@arm.com
8035517Snate@binkert.orgnamespace Trace {
80410455SCurtis.Dunham@arm.com
80510455SCurtis.Dunham@arm.comenum Flags {'''
80610455SCurtis.Dunham@arm.com
80710455SCurtis.Dunham@arm.com    # Generate the enum.  Base flags come first, then compound flags.
80810455SCurtis.Dunham@arm.com    idx = 0
80910455SCurtis.Dunham@arm.com    for flag, compound, desc in allFlags:
81010455SCurtis.Dunham@arm.com        if not compound:
81110455SCurtis.Dunham@arm.com            print >>f, '    %s = %d,' % (flag, idx)
81210685Sandreas.hansson@arm.com            idx += 1
81310455SCurtis.Dunham@arm.com
81410685Sandreas.hansson@arm.com    numBaseFlags = idx
81510455SCurtis.Dunham@arm.com    print >>f, '    NumFlags = %d,' % idx
8165517Snate@binkert.org
81710455SCurtis.Dunham@arm.com    # put a comment in here to separate base from compound flags
8188232Snate@binkert.org    print >>f, '''
8198232Snate@binkert.org// The remaining enum values are *not* valid indices for Trace::flags.
8205517Snate@binkert.org// They are "compound" flags, which correspond to sets of base
8217673Snate@binkert.org// flags, and are used by changeFlag.'''
8225517Snate@binkert.org
8238232Snate@binkert.org    print >>f, '    All = %d,' % idx
8248232Snate@binkert.org    idx += 1
8255517Snate@binkert.org    for flag, compound, desc in allFlags:
8268232Snate@binkert.org        if compound:
8278232Snate@binkert.org            print >>f, '    %s = %d,' % (flag, idx)
8288232Snate@binkert.org            idx += 1
8297673Snate@binkert.org
8305517Snate@binkert.org    numCompoundFlags = idx - numBaseFlags
8315517Snate@binkert.org    print >>f, '    NumCompoundFlags = %d' % numCompoundFlags
8327673Snate@binkert.org
8335517Snate@binkert.org    # trailer boilerplate
83410455SCurtis.Dunham@arm.com    print >>f, '''\
8355517Snate@binkert.org}; // enum Flags
8365517Snate@binkert.org
8378232Snate@binkert.org// Array of strings for SimpleEnumParam
8388232Snate@binkert.orgextern const char *flagStrings[];
8395517Snate@binkert.orgextern const int numFlagStrings;
8408232Snate@binkert.org
8418232Snate@binkert.org// Array of arraay pointers: for each compound flag, gives the list of
8425517Snate@binkert.org// base flags to set.  Inidividual flag arrays are terminated by -1.
8438232Snate@binkert.orgextern const Flags *compoundFlags[];
8448232Snate@binkert.org
8458232Snate@binkert.org/* namespace Trace */ }
8465517Snate@binkert.org
8478232Snate@binkert.org#endif // __BASE_TRACE_FLAGS_HH__
8488232Snate@binkert.org'''
8498232Snate@binkert.org
8508232Snate@binkert.org    f.close()
8518232Snate@binkert.org
8528232Snate@binkert.orgflags = map(Value, trace_flags.values())
8535517Snate@binkert.orgenv.Command('base/traceflags.py', flags, traceFlagsPy)
8548232Snate@binkert.orgPySource('m5', 'base/traceflags.py')
8558232Snate@binkert.org
8565517Snate@binkert.orgenv.Command('base/traceflags.hh', flags, traceFlagsHH)
8578232Snate@binkert.orgenv.Command('base/traceflags.cc', flags, traceFlagsCC)
8587673Snate@binkert.orgSource('base/traceflags.cc')
8595517Snate@binkert.org
8607673Snate@binkert.org# embed python files.  All .py files that have been indicated by a
8615517Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
8628232Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
8638232Snate@binkert.org# byte code, compress it, and then generate an assembly file that
8648232Snate@binkert.org# inserts the result into the data section with symbols indicating the
8655192Ssaidi@eecs.umich.edu# beginning, and end (and with the size at the end)
86610454SCurtis.Dunham@arm.comdef objectifyPyFile(target, source, env):
86710454SCurtis.Dunham@arm.com    '''Action function to compile a .py into a code object, marshal
8688232Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
86910455SCurtis.Dunham@arm.com    as just bytes with a label in the data section'''
87010455SCurtis.Dunham@arm.com
87110455SCurtis.Dunham@arm.com    src = file(str(source[0]), 'r').read()
87210455SCurtis.Dunham@arm.com    dst = file(str(target[0]), 'w')
8735192Ssaidi@eecs.umich.edu
87411077SCurtis.Dunham@arm.com    pysource = PySource.tnodes[source[0]]
87511330SCurtis.Dunham@arm.com    compiled = compile(src, pysource.debugname, 'exec')
87611077SCurtis.Dunham@arm.com    marshalled = marshal.dumps(compiled)
87711077SCurtis.Dunham@arm.com    compressed = zlib.compress(marshalled)
87811077SCurtis.Dunham@arm.com    data = compressed
87911330SCurtis.Dunham@arm.com
88011077SCurtis.Dunham@arm.com    # Some C/C++ compilers prepend an underscore to global symbol
8817674Snate@binkert.org    # names, so if they're going to do that, we need to prepend that
8825522Snate@binkert.org    # leading underscore to globals in the assembly file.
8835522Snate@binkert.org    if env['LEADING_UNDERSCORE']:
8847674Snate@binkert.org        sym = '_' + pysource.symname
8857674Snate@binkert.org    else:
8867674Snate@binkert.org        sym = pysource.symname
8877674Snate@binkert.org
8887674Snate@binkert.org    step = 16
8897674Snate@binkert.org    print >>dst, ".data"
8907674Snate@binkert.org    print >>dst, ".globl %s_beg" % sym
8917674Snate@binkert.org    print >>dst, ".globl %s_end" % sym
8925522Snate@binkert.org    print >>dst, "%s_beg:" % sym
8935522Snate@binkert.org    for i in xrange(0, len(data), step):
8945522Snate@binkert.org        x = array.array('B', data[i:i+step])
8955517Snate@binkert.org        print >>dst, ".byte", ','.join([str(d) for d in x])
8965522Snate@binkert.org    print >>dst, "%s_end:" % sym
8975517Snate@binkert.org    print >>dst, ".long %d" % len(marshalled)
8986143Snate@binkert.org
8996727Ssteve.reinhardt@amd.comfor source in PySource.all:
9005522Snate@binkert.org    env.Command(source.assembly, source.tnode, objectifyPyFile)
9015522Snate@binkert.org    Source(source.assembly)
9025522Snate@binkert.org
9037674Snate@binkert.org# Generate init_python.cc which creates a bunch of EmbeddedPyModule
9045517Snate@binkert.org# structs that describe the embedded python code.  One such struct
9057673Snate@binkert.org# contains information about the importer that python uses to get at
9067673Snate@binkert.org# the embedded files, and then there's a list of all of the rest that
9077674Snate@binkert.org# the importer uses to load the rest on demand.
9087673Snate@binkert.orgdef pythonInit(target, source, env):
9097674Snate@binkert.org    dst = file(str(target[0]), 'w')
9107674Snate@binkert.org
9118946Sandreas.hansson@arm.com    def dump_mod(sym, endchar=','):
9127674Snate@binkert.org        pysource = PySource.symnames[sym]
9137674Snate@binkert.org        print >>dst, '    { "%s",' % pysource.arcname
9147674Snate@binkert.org        print >>dst, '      "%s",' % pysource.modpath
9155522Snate@binkert.org        print >>dst, '       %s_beg, %s_end,' % (sym, sym)
9165522Snate@binkert.org        print >>dst, '       %s_end - %s_beg,' % (sym, sym)
9177674Snate@binkert.org        print >>dst, '       *(int *)%s_end }%s'  % (sym, endchar)
9187674Snate@binkert.org    
91911308Santhony.gutierrez@amd.com    print >>dst, '#include "sim/init.hh"'
9207674Snate@binkert.org
9217673Snate@binkert.org    for sym in source:
9227674Snate@binkert.org        sym = sym.get_contents()
9237674Snate@binkert.org        print >>dst, "extern const char %s_beg[], %s_end[];" % (sym, sym)
9247674Snate@binkert.org
9257674Snate@binkert.org    print >>dst, "const EmbeddedPyModule embeddedPyImporter = "
9267674Snate@binkert.org    dump_mod("PyEMB_importer", endchar=';');
9277674Snate@binkert.org    print >>dst
9287674Snate@binkert.org
9297674Snate@binkert.org    print >>dst, "const EmbeddedPyModule embeddedPyModules[] = {"
9307811Ssteve.reinhardt@amd.com    for i,sym in enumerate(source):
9317674Snate@binkert.org        sym = sym.get_contents()
9327673Snate@binkert.org        if sym == "PyEMB_importer":
9335522Snate@binkert.org            # Skip the importer since we've already exported it
9346143Snate@binkert.org            continue
93510453SAndrew.Bardsley@arm.com        dump_mod(sym)
9367816Ssteve.reinhardt@amd.com    print >>dst, "    { 0, 0, 0, 0, 0, 0 }"
93710453SAndrew.Bardsley@arm.com    print >>dst, "};"
9384382Sbinkertn@umich.edu
9394382Sbinkertn@umich.edu
9404382Sbinkertn@umich.eduenv.Command('sim/init_python.cc',
9414382Sbinkertn@umich.edu            map(Value, (s.symname for s in PySource.all)),
9424382Sbinkertn@umich.edu            pythonInit)
9434382Sbinkertn@umich.eduSource('sim/init_python.cc')
9444382Sbinkertn@umich.edu
9454382Sbinkertn@umich.edu########################################################################
94610196SCurtis.Dunham@arm.com#
9474382Sbinkertn@umich.edu# Define binaries.  Each different build type (debug, opt, etc.) gets
9482655Sstever@eecs.umich.edu# a slightly different build environment.
9492655Sstever@eecs.umich.edu#
9502655Sstever@eecs.umich.edu
9512655Sstever@eecs.umich.edu# List of constructed environments to pass back to SConstruct
95212063Sgabeblack@google.comenvList = []
9535601Snate@binkert.org
9545601Snate@binkert.orgdate_source = Source('base/date.cc', skip_lib=True)
95512222Sgabeblack@google.com
95612222Sgabeblack@google.com# Function to create a new build environment as clone of current
95712222Sgabeblack@google.com# environment 'env' with modified object suffix and optional stripped
9585522Snate@binkert.org# binary.  Additional keyword arguments are appended to corresponding
9595863Snate@binkert.org# build environment vars.
9605601Snate@binkert.orgdef makeEnv(label, objsfx, strip = False, **kwargs):
9615601Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
9625601Snate@binkert.org    # name.  Use '_' instead.
9635559Snate@binkert.org    libname = 'm5_' + label
96411718Sjoseph.gross@amd.com    exename = 'm5.' + label
96511718Sjoseph.gross@amd.com
96611718Sjoseph.gross@amd.com    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
96711718Sjoseph.gross@amd.com    new_env.Label = label
96811718Sjoseph.gross@amd.com    new_env.Append(**kwargs)
96911718Sjoseph.gross@amd.com
97011718Sjoseph.gross@amd.com    swig_env = new_env.Clone()
97111718Sjoseph.gross@amd.com    swig_env.Append(CCFLAGS='-Werror')
97211718Sjoseph.gross@amd.com    if env['GCC']:
97311718Sjoseph.gross@amd.com        swig_env.Append(CCFLAGS='-Wno-uninitialized')
97411718Sjoseph.gross@amd.com        swig_env.Append(CCFLAGS='-Wno-sign-compare')
97510457Sandreas.hansson@arm.com        swig_env.Append(CCFLAGS='-Wno-parentheses')
97610457Sandreas.hansson@arm.com
97710457Sandreas.hansson@arm.com    werror_env = new_env.Clone()
97811718Sjoseph.gross@amd.com    werror_env.Append(CCFLAGS='-Werror')
97910457Sandreas.hansson@arm.com
98010457Sandreas.hansson@arm.com    def make_obj(source, static, extra_deps = None):
98110457Sandreas.hansson@arm.com        '''This function adds the specified source to the correct
98210457Sandreas.hansson@arm.com        build environment, and returns the corresponding SCons Object
98311342Sandreas.hansson@arm.com        nodes'''
9848737Skoansin.tan@gmail.com
98511342Sandreas.hansson@arm.com        if source.swig:
98611342Sandreas.hansson@arm.com            env = swig_env
98710457Sandreas.hansson@arm.com        elif source.Werror:
98811718Sjoseph.gross@amd.com            env = werror_env
98911718Sjoseph.gross@amd.com        else:
99011718Sjoseph.gross@amd.com            env = new_env
99111718Sjoseph.gross@amd.com
99211718Sjoseph.gross@amd.com        if static:
99311718Sjoseph.gross@amd.com            obj = env.StaticObject(source.tnode)
99411718Sjoseph.gross@amd.com        else:
99510457Sandreas.hansson@arm.com            obj = env.SharedObject(source.tnode)
99611718Sjoseph.gross@amd.com
99711500Sandreas.hansson@arm.com        if extra_deps:
99811500Sandreas.hansson@arm.com            env.Depends(obj, extra_deps)
99911342Sandreas.hansson@arm.com
100011342Sandreas.hansson@arm.com        return obj
10018945Ssteve.reinhardt@amd.com
100210686SAndreas.Sandberg@ARM.com    static_objs = [ make_obj(s, True) for s in Source.get(skip_lib=False)]
100310686SAndreas.Sandberg@ARM.com    shared_objs = [ make_obj(s, False) for s in Source.get(skip_lib=False)]
100410686SAndreas.Sandberg@ARM.com
100510686SAndreas.Sandberg@ARM.com    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
100610686SAndreas.Sandberg@ARM.com    static_objs.append(static_date)
100710686SAndreas.Sandberg@ARM.com    
10088945Ssteve.reinhardt@amd.com    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
10096143Snate@binkert.org    shared_objs.append(shared_date)
10106143Snate@binkert.org
10116143Snate@binkert.org    # First make a library of everything but main() so other programs can
10126143Snate@binkert.org    # link against m5.
10136143Snate@binkert.org    static_lib = new_env.StaticLibrary(libname, static_objs)
101411988Sandreas.sandberg@arm.com    shared_lib = new_env.SharedLibrary(libname, shared_objs)
10158945Ssteve.reinhardt@amd.com
10166143Snate@binkert.org    for target, sources in unit_tests:
10176143Snate@binkert.org        objs = [ make_obj(s, static=True) for s in sources ]
10186143Snate@binkert.org        new_env.Program("unittest/%s.%s" % (target, label), objs + static_objs)
10196143Snate@binkert.org
10206143Snate@binkert.org    # Now link a stub with main() and the static library.
10216143Snate@binkert.org    bin_objs = [make_obj(s, True) for s in Source.get(bin_only=True) ]
10226143Snate@binkert.org    progname = exename
10236143Snate@binkert.org    if strip:
10246143Snate@binkert.org        progname += '.unstripped'
10256143Snate@binkert.org
10266143Snate@binkert.org    targets = new_env.Program(progname, bin_objs + static_objs)
10276143Snate@binkert.org
10286143Snate@binkert.org    if strip:
102910453SAndrew.Bardsley@arm.com        if sys.platform == 'sunos5':
103010453SAndrew.Bardsley@arm.com            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
103111988Sandreas.sandberg@arm.com        else:
103211988Sandreas.sandberg@arm.com            cmd = 'strip $SOURCE -o $TARGET'
103310453SAndrew.Bardsley@arm.com        targets = new_env.Command(exename, progname, cmd)
103410453SAndrew.Bardsley@arm.com            
103510453SAndrew.Bardsley@arm.com    new_env.M5Binary = targets[0]
103611983Sgabeblack@google.com    envList.append(new_env)
103711983Sgabeblack@google.com
103811983Sgabeblack@google.com# Debug binary
103911983Sgabeblack@google.comccflags = {}
104011983Sgabeblack@google.comif env['GCC']:
104111983Sgabeblack@google.com    if sys.platform == 'sunos5':
104211983Sgabeblack@google.com        ccflags['debug'] = '-gstabs+'
104311983Sgabeblack@google.com    else:
104411983Sgabeblack@google.com        ccflags['debug'] = '-ggdb3'
104511983Sgabeblack@google.com    ccflags['opt'] = '-g -O3'
104611983Sgabeblack@google.com    ccflags['fast'] = '-O3'
104711983Sgabeblack@google.com    ccflags['prof'] = '-O3 -g -pg'
104811983Sgabeblack@google.comelif env['SUNCC']:
104911983Sgabeblack@google.com    ccflags['debug'] = '-g0'
105011983Sgabeblack@google.com    ccflags['opt'] = '-g -O'
105111983Sgabeblack@google.com    ccflags['fast'] = '-fast'
105211983Sgabeblack@google.com    ccflags['prof'] = '-fast -g -pg'
105311983Sgabeblack@google.comelif env['ICC']:
105412063Sgabeblack@google.com    ccflags['debug'] = '-g -O0'
105512063Sgabeblack@google.com    ccflags['opt'] = '-g -O'
105612063Sgabeblack@google.com    ccflags['fast'] = '-fast'
105712063Sgabeblack@google.com    ccflags['prof'] = '-fast -g -pg'
105812063Sgabeblack@google.comelse:
105912063Sgabeblack@google.com    print 'Unknown compiler, please fix compiler options'
106012063Sgabeblack@google.com    Exit(1)
106112063Sgabeblack@google.com
106211983Sgabeblack@google.commakeEnv('debug', '.do',
106311983Sgabeblack@google.com        CCFLAGS = Split(ccflags['debug']),
106411983Sgabeblack@google.com        CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
106511983Sgabeblack@google.com
106611983Sgabeblack@google.com# Optimized binary
106711983Sgabeblack@google.commakeEnv('opt', '.o',
106811983Sgabeblack@google.com        CCFLAGS = Split(ccflags['opt']),
106911983Sgabeblack@google.com        CPPDEFINES = ['TRACING_ON=1'])
107011983Sgabeblack@google.com
107111983Sgabeblack@google.com# "Fast" binary
107211983Sgabeblack@google.commakeEnv('fast', '.fo', strip = True,
107311983Sgabeblack@google.com        CCFLAGS = Split(ccflags['fast']),
107411983Sgabeblack@google.com        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
10756143Snate@binkert.org
10766143Snate@binkert.org# Profiled binary
10776143Snate@binkert.orgmakeEnv('prof', '.po',
107810453SAndrew.Bardsley@arm.com        CCFLAGS = Split(ccflags['prof']),
10796143Snate@binkert.org        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
10806240Snate@binkert.org        LINKFLAGS = '-pg')
10815554Snate@binkert.org
10825522Snate@binkert.orgReturn('envList')
10835522Snate@binkert.org