SConscript revision 12063
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# Redistribution and use in source and binary forms, with or without
7955SN/A# modification, are permitted provided that the following conditions are
8955SN/A# met: redistributions of source code must retain the above copyright
9955SN/A# notice, this list of conditions and the following disclaimer;
10955SN/A# redistributions in binary form must reproduce the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer in the
12955SN/A# documentation and/or other materials provided with the distribution;
13955SN/A# neither the name of the copyright holders nor the names of its
14955SN/A# contributors may be used to endorse or promote products derived from
15955SN/A# this software without specific prior written permission.
16955SN/A#
17955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
294762Snate@binkert.org# Authors: Nathan Binkert
30955SN/A
315522Snate@binkert.orgimport array
326143Snate@binkert.orgimport bisect
334762Snate@binkert.orgimport imp
345522Snate@binkert.orgimport marshal
35955SN/Aimport os
365522Snate@binkert.orgimport re
37955SN/Aimport subprocess
385522Snate@binkert.orgimport sys
394202Sbinkertn@umich.eduimport zlib
405742Snate@binkert.org
41955SN/Afrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
424381Sbinkertn@umich.edu
434381Sbinkertn@umich.eduimport SCons
448334Snate@binkert.org
45955SN/A# This file defines how to build a particular configuration of gem5
46955SN/A# based on variable settings in the 'env' build environment.
474202Sbinkertn@umich.edu
48955SN/AImport('*')
494382Sbinkertn@umich.edu
504382Sbinkertn@umich.edu# Children need to see the environment
514382Sbinkertn@umich.eduExport('env')
526654Snate@binkert.org
535517Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
548614Sgblack@eecs.umich.edu
557674Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
566143Snate@binkert.org
576143Snate@binkert.org########################################################################
586143Snate@binkert.org# Code for adding source files of various types
598233Snate@binkert.org#
608233Snate@binkert.org# When specifying a source file of some type, a set of guards can be
618233Snate@binkert.org# specified for that file.  When get() is used to find the files, if
628233Snate@binkert.org# get specifies a set of filters, only files that match those filters
638233Snate@binkert.org# will be accepted (unspecified filters on files are assumed to be
648334Snate@binkert.org# false).  Current filters are:
658334Snate@binkert.org#     main -- specifies the gem5 main() function
6610453SAndrew.Bardsley@arm.com#     skip_lib -- do not put this file into the gem5 library
6710453SAndrew.Bardsley@arm.com#     skip_no_python -- do not put this file into a no_python library
688233Snate@binkert.org#       as it embeds compiled Python
698233Snate@binkert.org#     <unittest> -- unit tests use filters based on the unit test name
708233Snate@binkert.org#
718233Snate@binkert.org# A parent can now be specified for a source file and default filter
728233Snate@binkert.org# values will be retrieved recursively from parents (children override
738233Snate@binkert.org# parents).
746143Snate@binkert.org#
758233Snate@binkert.orgdef guarded_source_iterator(sources, **guards):
768233Snate@binkert.org    '''Iterate over a set of sources, gated by a set of guards.'''
778233Snate@binkert.org    for src in sources:
786143Snate@binkert.org        for flag,value in guards.iteritems():
796143Snate@binkert.org            # if the flag is found and has a different value, skip
806143Snate@binkert.org            # this file
8111308Santhony.gutierrez@amd.com            if src.all_guards.get(flag, False) != value:
828233Snate@binkert.org                break
838233Snate@binkert.org        else:
848233Snate@binkert.org            yield src
856143Snate@binkert.org
868233Snate@binkert.orgclass SourceMeta(type):
878233Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
888233Snate@binkert.org    particular type and has a get function for finding all functions
898233Snate@binkert.org    of a certain type that match a set of guards'''
906143Snate@binkert.org    def __init__(cls, name, bases, dict):
916143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
926143Snate@binkert.org        cls.all = []
934762Snate@binkert.org
946143Snate@binkert.org    def get(cls, **guards):
958233Snate@binkert.org        '''Find all files that match the specified guards.  If a source
968233Snate@binkert.org        file does not specify a flag, the default is False'''
978233Snate@binkert.org        for s in guarded_source_iterator(cls.all, **guards):
988233Snate@binkert.org            yield s
998233Snate@binkert.org
1006143Snate@binkert.orgclass SourceFile(object):
1018233Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1028233Snate@binkert.org    This includes, the source node, target node, various manipulations
1038233Snate@binkert.org    of those.  A source file also specifies a set of guards which
1048233Snate@binkert.org    describing which builds the source file applies to.  A parent can
1056143Snate@binkert.org    also be specified to get default guards from'''
1066143Snate@binkert.org    __metaclass__ = SourceMeta
1076143Snate@binkert.org    def __init__(self, source, parent=None, **guards):
1086143Snate@binkert.org        self.guards = guards
1096143Snate@binkert.org        self.parent = parent
1106143Snate@binkert.org
1116143Snate@binkert.org        tnode = source
1126143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1136143Snate@binkert.org            tnode = File(source)
1147065Snate@binkert.org
1156143Snate@binkert.org        self.tnode = tnode
1168233Snate@binkert.org        self.snode = tnode.srcnode()
1178233Snate@binkert.org
1188233Snate@binkert.org        for base in type(self).__mro__:
1198233Snate@binkert.org            if issubclass(base, SourceFile):
1208233Snate@binkert.org                base.all.append(self)
1218233Snate@binkert.org
1228233Snate@binkert.org    @property
1238233Snate@binkert.org    def filename(self):
1248233Snate@binkert.org        return str(self.tnode)
1258233Snate@binkert.org
1268233Snate@binkert.org    @property
1278233Snate@binkert.org    def dirname(self):
1288233Snate@binkert.org        return dirname(self.filename)
1298233Snate@binkert.org
1308233Snate@binkert.org    @property
1318233Snate@binkert.org    def basename(self):
1328233Snate@binkert.org        return basename(self.filename)
1338233Snate@binkert.org
1348233Snate@binkert.org    @property
1358233Snate@binkert.org    def extname(self):
1368233Snate@binkert.org        index = self.basename.rfind('.')
1378233Snate@binkert.org        if index <= 0:
1388233Snate@binkert.org            # dot files aren't extensions
1398233Snate@binkert.org            return self.basename, None
1408233Snate@binkert.org
1418233Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1428233Snate@binkert.org
1438233Snate@binkert.org    @property
1448233Snate@binkert.org    def all_guards(self):
1458233Snate@binkert.org        '''find all guards for this object getting default values
1468233Snate@binkert.org        recursively from its parents'''
1476143Snate@binkert.org        guards = {}
1486143Snate@binkert.org        if self.parent:
1496143Snate@binkert.org            guards.update(self.parent.guards)
1506143Snate@binkert.org        guards.update(self.guards)
1516143Snate@binkert.org        return guards
1526143Snate@binkert.org
1539982Satgutier@umich.edu    def __lt__(self, other): return self.filename < other.filename
15410196SCurtis.Dunham@arm.com    def __le__(self, other): return self.filename <= other.filename
15510196SCurtis.Dunham@arm.com    def __gt__(self, other): return self.filename > other.filename
15610196SCurtis.Dunham@arm.com    def __ge__(self, other): return self.filename >= other.filename
15710196SCurtis.Dunham@arm.com    def __eq__(self, other): return self.filename == other.filename
15810196SCurtis.Dunham@arm.com    def __ne__(self, other): return self.filename != other.filename
15910196SCurtis.Dunham@arm.com
16010196SCurtis.Dunham@arm.com    @staticmethod
16110196SCurtis.Dunham@arm.com    def done():
1626143Snate@binkert.org        def disabled(cls, name, *ignored):
1636143Snate@binkert.org            raise RuntimeError("Additional SourceFile '%s'" % name,\
1648945Ssteve.reinhardt@amd.com                  "declared, but targets deps are already fixed.")
1658233Snate@binkert.org        SourceFile.__init__ = disabled
1668233Snate@binkert.org
1676143Snate@binkert.org
1688945Ssteve.reinhardt@amd.comclass Source(SourceFile):
1696143Snate@binkert.org    current_group = None
1706143Snate@binkert.org    source_groups = { None : [] }
1716143Snate@binkert.org
1726143Snate@binkert.org    @classmethod
1735522Snate@binkert.org    def set_group(cls, group):
1746143Snate@binkert.org        if not group in Source.source_groups:
1756143Snate@binkert.org            Source.source_groups[group] = []
1766143Snate@binkert.org        Source.current_group = group
1779982Satgutier@umich.edu
1788233Snate@binkert.org    '''Add a c/c++ source file to the build'''
1798233Snate@binkert.org    def __init__(self, source, Werror=True, **guards):
1808233Snate@binkert.org        '''specify the source file, and any guards'''
1816143Snate@binkert.org        super(Source, self).__init__(source, **guards)
1826143Snate@binkert.org
1836143Snate@binkert.org        self.Werror = Werror
1846143Snate@binkert.org
1855522Snate@binkert.org        Source.source_groups[Source.current_group].append(self)
1865522Snate@binkert.org
1875522Snate@binkert.orgclass PySource(SourceFile):
1885522Snate@binkert.org    '''Add a python source file to the named package'''
1895604Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
1905604Snate@binkert.org    modules = {}
1916143Snate@binkert.org    tnodes = {}
1926143Snate@binkert.org    symnames = {}
1934762Snate@binkert.org
1944762Snate@binkert.org    def __init__(self, package, source, **guards):
1956143Snate@binkert.org        '''specify the python package, the source file, and any guards'''
1966727Ssteve.reinhardt@amd.com        super(PySource, self).__init__(source, **guards)
1976727Ssteve.reinhardt@amd.com
1986727Ssteve.reinhardt@amd.com        modname,ext = self.extname
1994762Snate@binkert.org        assert ext == 'py'
2006143Snate@binkert.org
2016143Snate@binkert.org        if package:
2026143Snate@binkert.org            path = package.split('.')
2036143Snate@binkert.org        else:
2046727Ssteve.reinhardt@amd.com            path = []
2056143Snate@binkert.org
2067674Snate@binkert.org        modpath = path[:]
2077674Snate@binkert.org        if modname != '__init__':
2085604Snate@binkert.org            modpath += [ modname ]
2096143Snate@binkert.org        modpath = '.'.join(modpath)
2106143Snate@binkert.org
2116143Snate@binkert.org        arcpath = path + [ self.basename ]
2124762Snate@binkert.org        abspath = self.snode.abspath
2136143Snate@binkert.org        if not exists(abspath):
2144762Snate@binkert.org            abspath = self.tnode.abspath
2154762Snate@binkert.org
2164762Snate@binkert.org        self.package = package
2176143Snate@binkert.org        self.modname = modname
2186143Snate@binkert.org        self.modpath = modpath
2194762Snate@binkert.org        self.arcname = joinpath(*arcpath)
2208233Snate@binkert.org        self.abspath = abspath
2218233Snate@binkert.org        self.compiled = File(self.filename + 'c')
2228233Snate@binkert.org        self.cpp = File(self.filename + '.cc')
2238233Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2246143Snate@binkert.org
2256143Snate@binkert.org        PySource.modules[modpath] = self
2264762Snate@binkert.org        PySource.tnodes[self.tnode] = self
2276143Snate@binkert.org        PySource.symnames[self.symname] = self
2284762Snate@binkert.org
2296143Snate@binkert.orgclass SimObject(PySource):
2304762Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2316143Snate@binkert.org    it to a list of sim object modules'''
2328233Snate@binkert.org
2338233Snate@binkert.org    fixed = False
23410453SAndrew.Bardsley@arm.com    modnames = []
2356143Snate@binkert.org
2366143Snate@binkert.org    def __init__(self, source, **guards):
2376143Snate@binkert.org        '''Specify the source file and any guards (automatically in
2386143Snate@binkert.org        the m5.objects package)'''
2396143Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, **guards)
2406143Snate@binkert.org        if self.fixed:
2416143Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
2426143Snate@binkert.org
24310453SAndrew.Bardsley@arm.com        bisect.insort_right(SimObject.modnames, self.modname)
24410453SAndrew.Bardsley@arm.com
245955SN/Aclass ProtoBuf(SourceFile):
2469396Sandreas.hansson@arm.com    '''Add a Protocol Buffer to build'''
2479396Sandreas.hansson@arm.com
2489396Sandreas.hansson@arm.com    def __init__(self, source, **guards):
2499396Sandreas.hansson@arm.com        '''Specify the source file, and any guards'''
2509396Sandreas.hansson@arm.com        super(ProtoBuf, self).__init__(source, **guards)
2519396Sandreas.hansson@arm.com
2529396Sandreas.hansson@arm.com        # Get the file name and the extension
2539396Sandreas.hansson@arm.com        modname,ext = self.extname
2549396Sandreas.hansson@arm.com        assert ext == 'proto'
2559396Sandreas.hansson@arm.com
2569396Sandreas.hansson@arm.com        # Currently, we stick to generating the C++ headers, so we
2579396Sandreas.hansson@arm.com        # only need to track the source and header.
2589396Sandreas.hansson@arm.com        self.cc_file = File(modname + '.pb.cc')
2599930Sandreas.hansson@arm.com        self.hh_file = File(modname + '.pb.h')
2609930Sandreas.hansson@arm.com
2619396Sandreas.hansson@arm.comclass UnitTest(object):
2628235Snate@binkert.org    '''Create a UnitTest'''
2638235Snate@binkert.org
2646143Snate@binkert.org    all = []
2658235Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
2669003SAli.Saidi@ARM.com        '''Specify the target name and any sources.  Sources that are
2678235Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2688235Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2698235Snate@binkert.org        target.'''
2708235Snate@binkert.org
2718235Snate@binkert.org        srcs = []
2728235Snate@binkert.org        for src in sources:
2738235Snate@binkert.org            if not isinstance(src, SourceFile):
2748235Snate@binkert.org                src = Source(src, skip_lib=True)
2758235Snate@binkert.org            src.guards[target] = True
2768235Snate@binkert.org            srcs.append(src)
2778235Snate@binkert.org
2788235Snate@binkert.org        self.sources = srcs
2798235Snate@binkert.org        self.target = target
2808235Snate@binkert.org        self.main = kwargs.get('main', False)
2819003SAli.Saidi@ARM.com        UnitTest.all.append(self)
2828235Snate@binkert.org
2835584Snate@binkert.org# Children should have access
2844382Sbinkertn@umich.eduExport('Source')
2854202Sbinkertn@umich.eduExport('PySource')
2864382Sbinkertn@umich.eduExport('SimObject')
2874382Sbinkertn@umich.eduExport('ProtoBuf')
2884382Sbinkertn@umich.eduExport('UnitTest')
2899396Sandreas.hansson@arm.com
2905584Snate@binkert.org########################################################################
2914382Sbinkertn@umich.edu#
2924382Sbinkertn@umich.edu# Debug Flags
2934382Sbinkertn@umich.edu#
2948232Snate@binkert.orgdebug_flags = {}
2955192Ssaidi@eecs.umich.edudef DebugFlag(name, desc=None):
2968232Snate@binkert.org    if name in debug_flags:
2978232Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2988232Snate@binkert.org    debug_flags[name] = (name, (), desc)
2995192Ssaidi@eecs.umich.edu
3008232Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
3015192Ssaidi@eecs.umich.edu    if name in debug_flags:
3025799Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3038232Snate@binkert.org
3045192Ssaidi@eecs.umich.edu    compound = tuple(flags)
3055192Ssaidi@eecs.umich.edu    debug_flags[name] = (name, compound, desc)
3065192Ssaidi@eecs.umich.edu
3078232Snate@binkert.orgExport('DebugFlag')
3085192Ssaidi@eecs.umich.eduExport('CompoundFlag')
3098232Snate@binkert.org
3105192Ssaidi@eecs.umich.edu########################################################################
3115192Ssaidi@eecs.umich.edu#
3125192Ssaidi@eecs.umich.edu# Set some compiler variables
3135192Ssaidi@eecs.umich.edu#
3144382Sbinkertn@umich.edu
3154382Sbinkertn@umich.edu# Include file paths are rooted in this directory.  SCons will
3164382Sbinkertn@umich.edu# automatically expand '.' to refer to both the source directory and
3172667Sstever@eecs.umich.edu# the corresponding build directory to pick up generated include
3182667Sstever@eecs.umich.edu# files.
3192667Sstever@eecs.umich.eduenv.Append(CPPPATH=Dir('.'))
3202667Sstever@eecs.umich.edu
3212667Sstever@eecs.umich.edufor extra_dir in extras_dir_list:
3222667Sstever@eecs.umich.edu    env.Append(CPPPATH=Dir(extra_dir))
3235742Snate@binkert.org
3245742Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3255742Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3265793Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3278334Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3285793Snate@binkert.org
3295793Snate@binkert.org########################################################################
3305793Snate@binkert.org#
3314382Sbinkertn@umich.edu# Walk the tree and execute all SConscripts in subdirectories
3324762Snate@binkert.org#
3335344Sstever@gmail.com
3344382Sbinkertn@umich.eduhere = Dir('.').srcnode().abspath
3355341Sstever@gmail.comfor root, dirs, files in os.walk(base_dir, topdown=True):
3365742Snate@binkert.org    if root == here:
3375742Snate@binkert.org        # we don't want to recurse back into this SConscript
3385742Snate@binkert.org        continue
3395742Snate@binkert.org
3405742Snate@binkert.org    if 'SConscript' in files:
3414762Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3425742Snate@binkert.org        Source.set_group(build_dir)
3435742Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3447722Sgblack@eecs.umich.edu
3455742Snate@binkert.orgfor extra_dir in extras_dir_list:
3465742Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3475742Snate@binkert.org
3489930Sandreas.hansson@arm.com    # Also add the corresponding build directory to pick up generated
3499930Sandreas.hansson@arm.com    # include files.
3509930Sandreas.hansson@arm.com    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3519930Sandreas.hansson@arm.com
3529930Sandreas.hansson@arm.com    for root, dirs, files in os.walk(extra_dir, topdown=True):
3535742Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3548242Sbradley.danofsky@amd.com        if 'build' in dirs:
3558242Sbradley.danofsky@amd.com            dirs.remove('build')
3568242Sbradley.danofsky@amd.com
3578242Sbradley.danofsky@amd.com        if 'SConscript' in files:
3585341Sstever@gmail.com            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3595742Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3607722Sgblack@eecs.umich.edu
3614773Snate@binkert.orgfor opt in export_vars:
3626108Snate@binkert.org    env.ConfigFile(opt)
3631858SN/A
3641085SN/Adef makeTheISA(source, target, env):
3656658Snate@binkert.org    isas = [ src.get_contents() for src in source ]
3666658Snate@binkert.org    target_isa = env['TARGET_ISA']
3677673Snate@binkert.org    def define(isa):
3686658Snate@binkert.org        return isa.upper() + '_ISA'
3696658Snate@binkert.org
37011308Santhony.gutierrez@amd.com    def namespace(isa):
3716658Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
37211308Santhony.gutierrez@amd.com
3736658Snate@binkert.org
3746658Snate@binkert.org    code = code_formatter()
3757673Snate@binkert.org    code('''\
3767673Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3777673Snate@binkert.org#define __CONFIG_THE_ISA_HH__
3787673Snate@binkert.org
3797673Snate@binkert.org''')
3807673Snate@binkert.org
3817673Snate@binkert.org    # create defines for the preprocessing and compile-time determination
38210467Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
3836658Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
3847673Snate@binkert.org    code()
38510467Sandreas.hansson@arm.com
38610467Sandreas.hansson@arm.com    # create an enum for any run-time determination of the ISA, we
38710467Sandreas.hansson@arm.com    # reuse the same name as the namespaces
38810467Sandreas.hansson@arm.com    code('enum class Arch {')
38910467Sandreas.hansson@arm.com    for i,isa in enumerate(isas):
39010467Sandreas.hansson@arm.com        if i + 1 == len(isas):
39110467Sandreas.hansson@arm.com            code('  $0 = $1', namespace(isa), define(isa))
39210467Sandreas.hansson@arm.com        else:
39310467Sandreas.hansson@arm.com            code('  $0 = $1,', namespace(isa), define(isa))
39410467Sandreas.hansson@arm.com    code('};')
39510467Sandreas.hansson@arm.com
3967673Snate@binkert.org    code('''
3977673Snate@binkert.org
3987673Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
3997673Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
4007673Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
4019048SAli.Saidi@ARM.com
4027673Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
4037673Snate@binkert.org
4047673Snate@binkert.org    code.write(str(target[0]))
4057673Snate@binkert.org
4066658Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4077756SAli.Saidi@ARM.com            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4087816Ssteve.reinhardt@amd.com
4096658Snate@binkert.orgdef makeTheGPUISA(source, target, env):
41011308Santhony.gutierrez@amd.com    isas = [ src.get_contents() for src in source ]
41111308Santhony.gutierrez@amd.com    target_gpu_isa = env['TARGET_GPU_ISA']
41211308Santhony.gutierrez@amd.com    def define(isa):
41311308Santhony.gutierrez@amd.com        return isa.upper() + '_ISA'
41411308Santhony.gutierrez@amd.com
41511308Santhony.gutierrez@amd.com    def namespace(isa):
41611308Santhony.gutierrez@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
41711308Santhony.gutierrez@amd.com
41811308Santhony.gutierrez@amd.com
41911308Santhony.gutierrez@amd.com    code = code_formatter()
42011308Santhony.gutierrez@amd.com    code('''\
42111308Santhony.gutierrez@amd.com#ifndef __CONFIG_THE_GPU_ISA_HH__
42211308Santhony.gutierrez@amd.com#define __CONFIG_THE_GPU_ISA_HH__
42311308Santhony.gutierrez@amd.com
42411308Santhony.gutierrez@amd.com''')
42511308Santhony.gutierrez@amd.com
42611308Santhony.gutierrez@amd.com    # create defines for the preprocessing and compile-time determination
42711308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
42811308Santhony.gutierrez@amd.com        code('#define $0 $1', define(isa), i + 1)
42911308Santhony.gutierrez@amd.com    code()
43011308Santhony.gutierrez@amd.com
43111308Santhony.gutierrez@amd.com    # create an enum for any run-time determination of the ISA, we
43211308Santhony.gutierrez@amd.com    # reuse the same name as the namespaces
43311308Santhony.gutierrez@amd.com    code('enum class GPUArch {')
43411308Santhony.gutierrez@amd.com    for i,isa in enumerate(isas):
43511308Santhony.gutierrez@amd.com        if i + 1 == len(isas):
43611308Santhony.gutierrez@amd.com            code('  $0 = $1', namespace(isa), define(isa))
43711308Santhony.gutierrez@amd.com        else:
43811308Santhony.gutierrez@amd.com            code('  $0 = $1,', namespace(isa), define(isa))
43911308Santhony.gutierrez@amd.com    code('};')
44011308Santhony.gutierrez@amd.com
44111308Santhony.gutierrez@amd.com    code('''
44211308Santhony.gutierrez@amd.com
44311308Santhony.gutierrez@amd.com#define THE_GPU_ISA ${{define(target_gpu_isa)}}
44411308Santhony.gutierrez@amd.com#define TheGpuISA ${{namespace(target_gpu_isa)}}
44511308Santhony.gutierrez@amd.com#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
44611308Santhony.gutierrez@amd.com
44711308Santhony.gutierrez@amd.com#endif // __CONFIG_THE_GPU_ISA_HH__''')
44811308Santhony.gutierrez@amd.com
44911308Santhony.gutierrez@amd.com    code.write(str(target[0]))
45011308Santhony.gutierrez@amd.com
45111308Santhony.gutierrez@amd.comenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
45211308Santhony.gutierrez@amd.com            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
45311308Santhony.gutierrez@amd.com
45411308Santhony.gutierrez@amd.com########################################################################
4554382Sbinkertn@umich.edu#
4564382Sbinkertn@umich.edu# Prevent any SimObjects from being added after this point, they
4574762Snate@binkert.org# should all have been added in the SConscripts above
4584762Snate@binkert.org#
4594762Snate@binkert.orgSimObject.fixed = True
4606654Snate@binkert.org
4616654Snate@binkert.orgclass DictImporter(object):
4625517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4635517Snate@binkert.org    map to arbitrary filenames.'''
4645517Snate@binkert.org    def __init__(self, modules):
4655517Snate@binkert.org        self.modules = modules
4665517Snate@binkert.org        self.installed = set()
4675517Snate@binkert.org
4685517Snate@binkert.org    def __del__(self):
4695517Snate@binkert.org        self.unload()
4705517Snate@binkert.org
4715517Snate@binkert.org    def unload(self):
4725517Snate@binkert.org        import sys
4735517Snate@binkert.org        for module in self.installed:
4745517Snate@binkert.org            del sys.modules[module]
4755517Snate@binkert.org        self.installed = set()
4765517Snate@binkert.org
4775517Snate@binkert.org    def find_module(self, fullname, path):
4785517Snate@binkert.org        if fullname == 'm5.defines':
4796654Snate@binkert.org            return self
4805517Snate@binkert.org
4815517Snate@binkert.org        if fullname == 'm5.objects':
4825517Snate@binkert.org            return self
4835517Snate@binkert.org
4845517Snate@binkert.org        if fullname.startswith('_m5'):
4855517Snate@binkert.org            return None
4865517Snate@binkert.org
4875517Snate@binkert.org        source = self.modules.get(fullname, None)
4886143Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
4896654Snate@binkert.org            return self
4905517Snate@binkert.org
4915517Snate@binkert.org        return None
4925517Snate@binkert.org
4935517Snate@binkert.org    def load_module(self, fullname):
4945517Snate@binkert.org        mod = imp.new_module(fullname)
4955517Snate@binkert.org        sys.modules[fullname] = mod
4965517Snate@binkert.org        self.installed.add(fullname)
4975517Snate@binkert.org
4985517Snate@binkert.org        mod.__loader__ = self
4995517Snate@binkert.org        if fullname == 'm5.objects':
5005517Snate@binkert.org            mod.__path__ = fullname.split('.')
5015517Snate@binkert.org            return mod
5025517Snate@binkert.org
5035517Snate@binkert.org        if fullname == 'm5.defines':
5046654Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
5056654Snate@binkert.org            return mod
5065517Snate@binkert.org
5075517Snate@binkert.org        source = self.modules[fullname]
5086143Snate@binkert.org        if source.modname == '__init__':
5096143Snate@binkert.org            mod.__path__ = source.modpath
5106143Snate@binkert.org        mod.__file__ = source.abspath
5116727Ssteve.reinhardt@amd.com
5125517Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
5136727Ssteve.reinhardt@amd.com
5145517Snate@binkert.org        return mod
5155517Snate@binkert.org
5165517Snate@binkert.orgimport m5.SimObject
5176654Snate@binkert.orgimport m5.params
5186654Snate@binkert.orgfrom m5.util import code_formatter
5197673Snate@binkert.org
5206654Snate@binkert.orgm5.SimObject.clear()
5216654Snate@binkert.orgm5.params.clear()
5226654Snate@binkert.org
5236654Snate@binkert.org# install the python importer so we can grab stuff from the source
5245517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
5255517Snate@binkert.org# else we won't know about them for the rest of the stuff.
5265517Snate@binkert.orgimporter = DictImporter(PySource.modules)
5276143Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
5285517Snate@binkert.org
5294762Snate@binkert.org# import all sim objects so we can populate the all_objects list
5305517Snate@binkert.org# make sure that we're working with a list, then let's sort it
5315517Snate@binkert.orgfor modname in SimObject.modnames:
5326143Snate@binkert.org    exec('from m5.objects import %s' % modname)
5336143Snate@binkert.org
5345517Snate@binkert.org# we need to unload all of the currently imported modules so that they
5355517Snate@binkert.org# will be re-imported the next time the sconscript is run
5365517Snate@binkert.orgimporter.unload()
5375517Snate@binkert.orgsys.meta_path.remove(importer)
5385517Snate@binkert.org
5395517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
5405517Snate@binkert.orgall_enums = m5.params.allEnums
5415517Snate@binkert.org
5425517Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
5439338SAndreas.Sandberg@arm.com    for param in obj._params.local.values():
5449338SAndreas.Sandberg@arm.com        # load the ptype attribute now because it depends on the
5459338SAndreas.Sandberg@arm.com        # current version of SimObject.allClasses, but when scons
5469338SAndreas.Sandberg@arm.com        # actually uses the value, all versions of
5479338SAndreas.Sandberg@arm.com        # SimObject.allClasses will have been loaded
5489338SAndreas.Sandberg@arm.com        param.ptype
5498596Ssteve.reinhardt@amd.com
5508596Ssteve.reinhardt@amd.com########################################################################
5518596Ssteve.reinhardt@amd.com#
5528596Ssteve.reinhardt@amd.com# calculate extra dependencies
5538596Ssteve.reinhardt@amd.com#
5548596Ssteve.reinhardt@amd.commodule_depends = ["m5", "m5.SimObject", "m5.params"]
5558596Ssteve.reinhardt@amd.comdepends = [ PySource.modules[dep].snode for dep in module_depends ]
5566143Snate@binkert.orgdepends.sort(key = lambda x: x.name)
5575517Snate@binkert.org
5586654Snate@binkert.org########################################################################
5596654Snate@binkert.org#
5606654Snate@binkert.org# Commands for the basic automatically generated python files
5616654Snate@binkert.org#
5626654Snate@binkert.org
5636654Snate@binkert.org# Generate Python file containing a dict specifying the current
5645517Snate@binkert.org# buildEnv flags.
5655517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
5665517Snate@binkert.org    build_env = source[0].get_contents()
5678596Ssteve.reinhardt@amd.com
5688596Ssteve.reinhardt@amd.com    code = code_formatter()
5694762Snate@binkert.org    code("""
5704762Snate@binkert.orgimport _m5.core
5714762Snate@binkert.orgimport m5.util
5724762Snate@binkert.org
5734762Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
5744762Snate@binkert.org
5757675Snate@binkert.orgcompileDate = _m5.core.compileDate
57610584Sandreas.hansson@arm.com_globals = globals()
5774762Snate@binkert.orgfor key,val in _m5.core.__dict__.iteritems():
5784762Snate@binkert.org    if key.startswith('flag_'):
5794762Snate@binkert.org        flag = key[5:]
5804762Snate@binkert.org        _globals[flag] = val
5814382Sbinkertn@umich.edudel _globals
5824382Sbinkertn@umich.edu""")
5835517Snate@binkert.org    code.write(target[0].abspath)
5846654Snate@binkert.org
5855517Snate@binkert.orgdefines_info = Value(build_env)
5868126Sgblack@eecs.umich.edu# Generate a file with all of the compile options in it
5876654Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
5887673Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
5896654Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
5906654Snate@binkert.org
5916654Snate@binkert.org# Generate python file containing info about the M5 source code
5926654Snate@binkert.orgdef makeInfoPyFile(target, source, env):
5936654Snate@binkert.org    code = code_formatter()
5946654Snate@binkert.org    for src in source:
5956654Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
5966669Snate@binkert.org        code('$src = ${{repr(data)}}')
5976669Snate@binkert.org    code.write(str(target[0]))
5986669Snate@binkert.org
5996669Snate@binkert.org# Generate a file that wraps the basic top level files
6006669Snate@binkert.orgenv.Command('python/m5/info.py',
6016669Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
6026654Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
6037673Snate@binkert.orgPySource('m5', 'python/m5/info.py')
6045517Snate@binkert.org
6058126Sgblack@eecs.umich.edu########################################################################
6065798Snate@binkert.org#
6077756SAli.Saidi@ARM.com# Create all of the SimObject param headers and enum headers
6087816Ssteve.reinhardt@amd.com#
6095798Snate@binkert.org
6105798Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
6115517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6125517Snate@binkert.org
6137673Snate@binkert.org    name = source[0].get_text_contents()
6145517Snate@binkert.org    obj = sim_objects[name]
6155517Snate@binkert.org
6167673Snate@binkert.org    code = code_formatter()
6177673Snate@binkert.org    obj.cxx_param_decl(code)
6185517Snate@binkert.org    code.write(target[0].abspath)
6195798Snate@binkert.org
6205798Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
6218333Snate@binkert.org    def body(target, source, env):
6227816Ssteve.reinhardt@amd.com        assert len(target) == 1 and len(source) == 1
6235798Snate@binkert.org
6245798Snate@binkert.org        name = str(source[0].get_contents())
6254762Snate@binkert.org        obj = sim_objects[name]
6264762Snate@binkert.org
6274762Snate@binkert.org        code = code_formatter()
6284762Snate@binkert.org        obj.cxx_config_param_file(code, is_header)
6294762Snate@binkert.org        code.write(target[0].abspath)
6308596Ssteve.reinhardt@amd.com    return body
6315517Snate@binkert.org
6325517Snate@binkert.orgdef createEnumStrings(target, source, env):
6335517Snate@binkert.org    assert len(target) == 1 and len(source) == 2
6345517Snate@binkert.org
6355517Snate@binkert.org    name = source[0].get_text_contents()
6367673Snate@binkert.org    use_python = source[1].read()
6378596Ssteve.reinhardt@amd.com    obj = all_enums[name]
6387673Snate@binkert.org
6395517Snate@binkert.org    code = code_formatter()
64010458Sandreas.hansson@arm.com    obj.cxx_def(code)
64110458Sandreas.hansson@arm.com    if use_python:
64210458Sandreas.hansson@arm.com        obj.pybind_def(code)
64310458Sandreas.hansson@arm.com    code.write(target[0].abspath)
64410458Sandreas.hansson@arm.com
64510458Sandreas.hansson@arm.comdef createEnumDecls(target, source, env):
64610458Sandreas.hansson@arm.com    assert len(target) == 1 and len(source) == 1
64710458Sandreas.hansson@arm.com
64810458Sandreas.hansson@arm.com    name = source[0].get_text_contents()
64910458Sandreas.hansson@arm.com    obj = all_enums[name]
65010458Sandreas.hansson@arm.com
65110458Sandreas.hansson@arm.com    code = code_formatter()
6528596Ssteve.reinhardt@amd.com    obj.cxx_decl(code)
6535517Snate@binkert.org    code.write(target[0].abspath)
6545517Snate@binkert.org
6555517Snate@binkert.orgdef createSimObjectPyBindWrapper(target, source, env):
6568596Ssteve.reinhardt@amd.com    name = source[0].get_text_contents()
6575517Snate@binkert.org    obj = sim_objects[name]
6587673Snate@binkert.org
6597673Snate@binkert.org    code = code_formatter()
6607673Snate@binkert.org    obj.pybind_decl(code)
6615517Snate@binkert.org    code.write(target[0].abspath)
6625517Snate@binkert.org
6635517Snate@binkert.org# Generate all of the SimObject param C++ struct header files
6645517Snate@binkert.orgparams_hh_files = []
6655517Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
6665517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6675517Snate@binkert.org    extra_deps = [ py_source.tnode ]
6687673Snate@binkert.org
6697673Snate@binkert.org    hh_file = File('params/%s.hh' % name)
6707673Snate@binkert.org    params_hh_files.append(hh_file)
6715517Snate@binkert.org    env.Command(hh_file, Value(name),
6728596Ssteve.reinhardt@amd.com                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6735517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
6745517Snate@binkert.org
6755517Snate@binkert.org# C++ parameter description files
6765517Snate@binkert.orgif GetOption('with_cxx_config'):
6775517Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
6787673Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
6797673Snate@binkert.org        extra_deps = [ py_source.tnode ]
6807673Snate@binkert.org
6815517Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
6828596Ssteve.reinhardt@amd.com        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
6837675Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
6847675Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
6857675Snate@binkert.org                    Transform("CXXCPRHH")))
6867675Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
6877675Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
6887675Snate@binkert.org                    Transform("CXXCPRCC")))
6898596Ssteve.reinhardt@amd.com        env.Depends(cxx_config_hh_file, depends + extra_deps +
6907675Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
6917675Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
6928596Ssteve.reinhardt@amd.com                    [cxx_config_hh_file])
6938596Ssteve.reinhardt@amd.com        Source(cxx_config_cc_file)
6948596Ssteve.reinhardt@amd.com
6958596Ssteve.reinhardt@amd.com    cxx_config_init_cc_file = File('cxx_config/init.cc')
6968596Ssteve.reinhardt@amd.com
6978596Ssteve.reinhardt@amd.com    def createCxxConfigInitCC(target, source, env):
6988596Ssteve.reinhardt@amd.com        assert len(target) == 1 and len(source) == 1
6998596Ssteve.reinhardt@amd.com
70010454SCurtis.Dunham@arm.com        code = code_formatter()
70110454SCurtis.Dunham@arm.com
70210454SCurtis.Dunham@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
70310454SCurtis.Dunham@arm.com            if not hasattr(simobj, 'abstract') or not simobj.abstract:
7048596Ssteve.reinhardt@amd.com                code('#include "cxx_config/${name}.hh"')
7054762Snate@binkert.org        code()
7066143Snate@binkert.org        code('void cxxConfigInit()')
7076143Snate@binkert.org        code('{')
7086143Snate@binkert.org        code.indent()
7094762Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7104762Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
7114762Snate@binkert.org                not simobj.abstract
7127756SAli.Saidi@ARM.com            if not_abstract and 'type' in simobj.__dict__:
7138596Ssteve.reinhardt@amd.com                code('cxx_config_directory["${name}"] = '
7144762Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
71510454SCurtis.Dunham@arm.com        code.dedent()
7164762Snate@binkert.org        code('}')
71710458Sandreas.hansson@arm.com        code.write(target[0].abspath)
71810458Sandreas.hansson@arm.com
71910458Sandreas.hansson@arm.com    py_source = PySource.modules[simobj.__module__]
72010458Sandreas.hansson@arm.com    extra_deps = [ py_source.tnode ]
72110458Sandreas.hansson@arm.com    env.Command(cxx_config_init_cc_file, Value(name),
72210458Sandreas.hansson@arm.com        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
72310458Sandreas.hansson@arm.com    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
72410458Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems())
72510458Sandreas.hansson@arm.com        if not hasattr(simobj, 'abstract') or not simobj.abstract]
72610458Sandreas.hansson@arm.com    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
72710458Sandreas.hansson@arm.com            [File('sim/cxx_config.hh')])
72810458Sandreas.hansson@arm.com    Source(cxx_config_init_cc_file)
72910458Sandreas.hansson@arm.com
73010458Sandreas.hansson@arm.com# Generate all enum header files
73110458Sandreas.hansson@arm.comfor name,enum in sorted(all_enums.iteritems()):
73210458Sandreas.hansson@arm.com    py_source = PySource.modules[enum.__module__]
73310458Sandreas.hansson@arm.com    extra_deps = [ py_source.tnode ]
73410458Sandreas.hansson@arm.com
73510458Sandreas.hansson@arm.com    cc_file = File('enums/%s.cc' % name)
73610458Sandreas.hansson@arm.com    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
73710458Sandreas.hansson@arm.com                MakeAction(createEnumStrings, Transform("ENUM STR")))
73810458Sandreas.hansson@arm.com    env.Depends(cc_file, depends + extra_deps)
73910458Sandreas.hansson@arm.com    Source(cc_file)
74010458Sandreas.hansson@arm.com
74110458Sandreas.hansson@arm.com    hh_file = File('enums/%s.hh' % name)
74210458Sandreas.hansson@arm.com    env.Command(hh_file, Value(name),
74310458Sandreas.hansson@arm.com                MakeAction(createEnumDecls, Transform("ENUMDECL")))
74410458Sandreas.hansson@arm.com    env.Depends(hh_file, depends + extra_deps)
74510458Sandreas.hansson@arm.com
74610458Sandreas.hansson@arm.com# Generate SimObject Python bindings wrapper files
74710458Sandreas.hansson@arm.comif env['USE_PYTHON']:
74810458Sandreas.hansson@arm.com    for name,simobj in sorted(sim_objects.iteritems()):
74910458Sandreas.hansson@arm.com        py_source = PySource.modules[simobj.__module__]
75010458Sandreas.hansson@arm.com        extra_deps = [ py_source.tnode ]
75110458Sandreas.hansson@arm.com        cc_file = File('python/_m5/param_%s.cc' % name)
75210458Sandreas.hansson@arm.com        env.Command(cc_file, Value(name),
75310458Sandreas.hansson@arm.com                    MakeAction(createSimObjectPyBindWrapper,
75410458Sandreas.hansson@arm.com                               Transform("SO PyBind")))
75510458Sandreas.hansson@arm.com        env.Depends(cc_file, depends + extra_deps)
75610458Sandreas.hansson@arm.com        Source(cc_file)
75710458Sandreas.hansson@arm.com
75810458Sandreas.hansson@arm.com# Build all protocol buffers if we have got protoc and protobuf available
75910458Sandreas.hansson@arm.comif env['HAVE_PROTOBUF']:
76010458Sandreas.hansson@arm.com    for proto in ProtoBuf.all:
76110458Sandreas.hansson@arm.com        # Use both the source and header as the target, and the .proto
76210458Sandreas.hansson@arm.com        # file as the source. When executing the protoc compiler, also
76310458Sandreas.hansson@arm.com        # specify the proto_path to avoid having the generated files
76410458Sandreas.hansson@arm.com        # include the path.
76510458Sandreas.hansson@arm.com        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
76610584Sandreas.hansson@arm.com                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
76710458Sandreas.hansson@arm.com                               '--proto_path ${SOURCE.dir} $SOURCE',
76810458Sandreas.hansson@arm.com                               Transform("PROTOC")))
76910458Sandreas.hansson@arm.com
77010458Sandreas.hansson@arm.com        # Add the C++ source file
77110458Sandreas.hansson@arm.com        Source(proto.cc_file, **proto.guards)
7728596Ssteve.reinhardt@amd.comelif ProtoBuf.all:
7735463Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
77410584Sandreas.hansson@arm.com    Exit(1)
7758596Ssteve.reinhardt@amd.com
7765463Snate@binkert.org#
7777756SAli.Saidi@ARM.com# Handle debug flags
7788596Ssteve.reinhardt@amd.com#
7794762Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
78010454SCurtis.Dunham@arm.com    assert(len(target) == 1 and len(source) == 1)
7817677Snate@binkert.org
7824762Snate@binkert.org    code = code_formatter()
7834762Snate@binkert.org
7846143Snate@binkert.org    # delay definition of CompoundFlags until after all the definition
7856143Snate@binkert.org    # of all constituent SimpleFlags
7866143Snate@binkert.org    comp_code = code_formatter()
7874762Snate@binkert.org
7884762Snate@binkert.org    # file header
7897756SAli.Saidi@ARM.com    code('''
7907816Ssteve.reinhardt@amd.com/*
7914762Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
79210454SCurtis.Dunham@arm.com */
7934762Snate@binkert.org
7944762Snate@binkert.org#include "base/debug.hh"
7954762Snate@binkert.org
7967756SAli.Saidi@ARM.comnamespace Debug {
7978596Ssteve.reinhardt@amd.com
7984762Snate@binkert.org''')
79910454SCurtis.Dunham@arm.com
8004762Snate@binkert.org    for name, flag in sorted(source[0].read().iteritems()):
8017677Snate@binkert.org        n, compound, desc = flag
8027756SAli.Saidi@ARM.com        assert n == name
8038596Ssteve.reinhardt@amd.com
8047675Snate@binkert.org        if not compound:
80510454SCurtis.Dunham@arm.com            code('SimpleFlag $name("$name", "$desc");')
8067677Snate@binkert.org        else:
8075517Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
8088596Ssteve.reinhardt@amd.com            comp_code.indent()
80910584Sandreas.hansson@arm.com            last = len(compound) - 1
8109248SAndreas.Sandberg@arm.com            for i,flag in enumerate(compound):
8119248SAndreas.Sandberg@arm.com                if i != last:
8128596Ssteve.reinhardt@amd.com                    comp_code('&$flag,')
8138596Ssteve.reinhardt@amd.com                else:
8148596Ssteve.reinhardt@amd.com                    comp_code('&$flag);')
8159248SAndreas.Sandberg@arm.com            comp_code.dedent()
8168596Ssteve.reinhardt@amd.com
8174762Snate@binkert.org    code.append(comp_code)
8187674Snate@binkert.org    code()
8197674Snate@binkert.org    code('} // namespace Debug')
8207674Snate@binkert.org
8217674Snate@binkert.org    code.write(str(target[0]))
8227674Snate@binkert.org
8237674Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
8247674Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8257674Snate@binkert.org
8267674Snate@binkert.org    val = eval(source[0].get_contents())
8277674Snate@binkert.org    name, compound, desc = val
8287674Snate@binkert.org
8297674Snate@binkert.org    code = code_formatter()
8307674Snate@binkert.org
8317674Snate@binkert.org    # file header boilerplate
83211308Santhony.gutierrez@amd.com    code('''\
8334762Snate@binkert.org/*
8346143Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8356143Snate@binkert.org */
8367756SAli.Saidi@ARM.com
8377816Ssteve.reinhardt@amd.com#ifndef __DEBUG_${name}_HH__
8388235Snate@binkert.org#define __DEBUG_${name}_HH__
8398596Ssteve.reinhardt@amd.com
8407756SAli.Saidi@ARM.comnamespace Debug {
8417816Ssteve.reinhardt@amd.com''')
84210454SCurtis.Dunham@arm.com
8438235Snate@binkert.org    if compound:
8444382Sbinkertn@umich.edu        code('class CompoundFlag;')
8459396Sandreas.hansson@arm.com    code('class SimpleFlag;')
8469396Sandreas.hansson@arm.com
8479396Sandreas.hansson@arm.com    if compound:
8489396Sandreas.hansson@arm.com        code('extern CompoundFlag $name;')
8499396Sandreas.hansson@arm.com        for flag in compound:
8509396Sandreas.hansson@arm.com            code('extern SimpleFlag $flag;')
8519396Sandreas.hansson@arm.com    else:
8529396Sandreas.hansson@arm.com        code('extern SimpleFlag $name;')
8539396Sandreas.hansson@arm.com
8549396Sandreas.hansson@arm.com    code('''
8559396Sandreas.hansson@arm.com}
8569396Sandreas.hansson@arm.com
85710454SCurtis.Dunham@arm.com#endif // __DEBUG_${name}_HH__
8589396Sandreas.hansson@arm.com''')
8599396Sandreas.hansson@arm.com
8609396Sandreas.hansson@arm.com    code.write(str(target[0]))
8619396Sandreas.hansson@arm.com
8629396Sandreas.hansson@arm.comfor name,flag in sorted(debug_flags.iteritems()):
8639396Sandreas.hansson@arm.com    n, compound, desc = flag
8648232Snate@binkert.org    assert n == name
8658232Snate@binkert.org
8668232Snate@binkert.org    hh_file = 'debug/%s.hh' % name
8678232Snate@binkert.org    env.Command(hh_file, Value(flag),
8688232Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
8696229Snate@binkert.org
87010455SCurtis.Dunham@arm.comenv.Command('debug/flags.cc', Value(debug_flags),
8716229Snate@binkert.org            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
87210455SCurtis.Dunham@arm.comSource('debug/flags.cc')
87310455SCurtis.Dunham@arm.com
87410455SCurtis.Dunham@arm.com# version tags
8755517Snate@binkert.orgtags = \
8765517Snate@binkert.orgenv.Command('sim/tags.cc', None,
8777673Snate@binkert.org            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
8785517Snate@binkert.org                       Transform("VER TAGS")))
87910455SCurtis.Dunham@arm.comenv.AlwaysBuild(tags)
8805517Snate@binkert.org
8815517Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
8828232Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
88310455SCurtis.Dunham@arm.com# library.  To do that, we compile the file to byte code, marshal the
88410455SCurtis.Dunham@arm.com# byte code, compress it, and then generate a c++ file that
88510455SCurtis.Dunham@arm.com# inserts the result into an array.
8867673Snate@binkert.orgdef embedPyFile(target, source, env):
8877673Snate@binkert.org    def c_str(string):
88810455SCurtis.Dunham@arm.com        if string is None:
88910455SCurtis.Dunham@arm.com            return "0"
89010455SCurtis.Dunham@arm.com        return '"%s"' % string
8915517Snate@binkert.org
89210455SCurtis.Dunham@arm.com    '''Action function to compile a .py into a code object, marshal
89310455SCurtis.Dunham@arm.com    it, compress it, and stick it into an asm file so the code appears
89410455SCurtis.Dunham@arm.com    as just bytes with a label in the data section'''
89510455SCurtis.Dunham@arm.com
89610455SCurtis.Dunham@arm.com    src = file(str(source[0]), 'r').read()
89710455SCurtis.Dunham@arm.com
89810455SCurtis.Dunham@arm.com    pysource = PySource.tnodes[source[0]]
89910455SCurtis.Dunham@arm.com    compiled = compile(src, pysource.abspath, 'exec')
90010685Sandreas.hansson@arm.com    marshalled = marshal.dumps(compiled)
90110455SCurtis.Dunham@arm.com    compressed = zlib.compress(marshalled)
90210685Sandreas.hansson@arm.com    data = compressed
90310455SCurtis.Dunham@arm.com    sym = pysource.symname
9045517Snate@binkert.org
90510455SCurtis.Dunham@arm.com    code = code_formatter()
9068232Snate@binkert.org    code('''\
9078232Snate@binkert.org#include "sim/init.hh"
9085517Snate@binkert.org
9097673Snate@binkert.orgnamespace {
9105517Snate@binkert.org
9118232Snate@binkert.orgconst uint8_t data_${sym}[] = {
9128232Snate@binkert.org''')
9135517Snate@binkert.org    code.indent()
9148232Snate@binkert.org    step = 16
9158232Snate@binkert.org    for i in xrange(0, len(data), step):
9168232Snate@binkert.org        x = array.array('B', data[i:i+step])
9177673Snate@binkert.org        code(''.join('%d,' % d for d in x))
9185517Snate@binkert.org    code.dedent()
9195517Snate@binkert.org
9207673Snate@binkert.org    code('''};
9215517Snate@binkert.org
92210455SCurtis.Dunham@arm.comEmbeddedPython embedded_${sym}(
9235517Snate@binkert.org    ${{c_str(pysource.arcname)}},
9245517Snate@binkert.org    ${{c_str(pysource.abspath)}},
9258232Snate@binkert.org    ${{c_str(pysource.modpath)}},
9268232Snate@binkert.org    data_${sym},
9275517Snate@binkert.org    ${{len(data)}},
9288232Snate@binkert.org    ${{len(marshalled)}});
9298232Snate@binkert.org
9305517Snate@binkert.org} // anonymous namespace
9318232Snate@binkert.org''')
9328232Snate@binkert.org    code.write(str(target[0]))
9338232Snate@binkert.org
9345517Snate@binkert.orgfor source in PySource.all:
9358232Snate@binkert.org    env.Command(source.cpp, source.tnode,
9368232Snate@binkert.org                MakeAction(embedPyFile, Transform("EMBED PY")))
9378232Snate@binkert.org    Source(source.cpp, skip_no_python=True)
9388232Snate@binkert.org
9398232Snate@binkert.org########################################################################
9408232Snate@binkert.org#
9415517Snate@binkert.org# Define binaries.  Each different build type (debug, opt, etc.) gets
9428232Snate@binkert.org# a slightly different build environment.
9438232Snate@binkert.org#
9445517Snate@binkert.org
9458232Snate@binkert.org# List of constructed environments to pass back to SConstruct
9467673Snate@binkert.orgdate_source = Source('base/date.cc', skip_lib=True)
9475517Snate@binkert.org
9487673Snate@binkert.org# Capture this directory for the closure makeEnv, otherwise when it is
9495517Snate@binkert.org# called, it won't know what directory it should use.
9508232Snate@binkert.orgvariant_dir = Dir('.').path
9518232Snate@binkert.orgdef variant(*path):
9528232Snate@binkert.org    return os.path.join(variant_dir, *path)
9535192Ssaidi@eecs.umich.edudef variantd(*path):
95410454SCurtis.Dunham@arm.com    return variant(*path)+'/'
95510454SCurtis.Dunham@arm.com
9568232Snate@binkert.org# Function to create a new build environment as clone of current
95710455SCurtis.Dunham@arm.com# environment 'env' with modified object suffix and optional stripped
95810455SCurtis.Dunham@arm.com# binary.  Additional keyword arguments are appended to corresponding
95910455SCurtis.Dunham@arm.com# build environment vars.
96010455SCurtis.Dunham@arm.comdef makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
96110455SCurtis.Dunham@arm.com    # SCons doesn't know to append a library suffix when there is a '.' in the
96210455SCurtis.Dunham@arm.com    # name.  Use '_' instead.
9635192Ssaidi@eecs.umich.edu    libname = variant('gem5_' + label)
96411077SCurtis.Dunham@arm.com    exename = variant('gem5.' + label)
96511330SCurtis.Dunham@arm.com    secondary_exename = variant('m5.' + label)
96611077SCurtis.Dunham@arm.com
96711077SCurtis.Dunham@arm.com    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
96811077SCurtis.Dunham@arm.com    new_env.Label = label
96911330SCurtis.Dunham@arm.com    new_env.Append(**kwargs)
97011077SCurtis.Dunham@arm.com
9717674Snate@binkert.org    if env['GCC']:
9725522Snate@binkert.org        # The address sanitizer is available for gcc >= 4.8
9735522Snate@binkert.org        if GetOption('with_asan'):
9747674Snate@binkert.org            if GetOption('with_ubsan') and \
9757674Snate@binkert.org                    compareVersions(env['GCC_VERSION'], '4.9') >= 0:
9767674Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
9777674Snate@binkert.org                                        '-fno-omit-frame-pointer'])
9787674Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
9797674Snate@binkert.org            else:
9807674Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address',
9817674Snate@binkert.org                                        '-fno-omit-frame-pointer'])
9825522Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address')
9835522Snate@binkert.org        # Only gcc >= 4.9 supports UBSan, so check both the version
9845522Snate@binkert.org        # and the command-line option before adding the compiler and
9855517Snate@binkert.org        # linker flags.
9865522Snate@binkert.org        elif GetOption('with_ubsan') and \
9875517Snate@binkert.org                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
9886143Snate@binkert.org            new_env.Append(CCFLAGS='-fsanitize=undefined')
9896727Ssteve.reinhardt@amd.com            new_env.Append(LINKFLAGS='-fsanitize=undefined')
9905522Snate@binkert.org
9915522Snate@binkert.org
9925522Snate@binkert.org    if env['CLANG']:
9937674Snate@binkert.org        # We require clang >= 3.1, so there is no need to check any
9945517Snate@binkert.org        # versions here.
9957673Snate@binkert.org        if GetOption('with_ubsan'):
9967673Snate@binkert.org            if GetOption('with_asan'):
9977674Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
9987673Snate@binkert.org                                        '-fno-omit-frame-pointer'])
9997674Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
10007674Snate@binkert.org            else:
10018946Sandreas.hansson@arm.com                new_env.Append(CCFLAGS='-fsanitize=undefined')
10027674Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=undefined')
10037674Snate@binkert.org
10047674Snate@binkert.org        elif GetOption('with_asan'):
10055522Snate@binkert.org            new_env.Append(CCFLAGS=['-fsanitize=address',
10065522Snate@binkert.org                                    '-fno-omit-frame-pointer'])
10077674Snate@binkert.org            new_env.Append(LINKFLAGS='-fsanitize=address')
10087674Snate@binkert.org
100911308Santhony.gutierrez@amd.com    werror_env = new_env.Clone()
10107674Snate@binkert.org    # Treat warnings as errors but white list some warnings that we
10117673Snate@binkert.org    # want to allow (e.g., deprecation warnings).
10127674Snate@binkert.org    werror_env.Append(CCFLAGS=['-Werror',
10137674Snate@binkert.org                               '-Wno-error=deprecated-declarations',
10147674Snate@binkert.org                               '-Wno-error=deprecated',
10157674Snate@binkert.org                               ])
10167674Snate@binkert.org
10177674Snate@binkert.org    def make_obj(source, static, extra_deps = None):
10187674Snate@binkert.org        '''This function adds the specified source to the correct
10197674Snate@binkert.org        build environment, and returns the corresponding SCons Object
10207811Ssteve.reinhardt@amd.com        nodes'''
10217674Snate@binkert.org
10227673Snate@binkert.org        if source.Werror:
10235522Snate@binkert.org            env = werror_env
10246143Snate@binkert.org        else:
102510453SAndrew.Bardsley@arm.com            env = new_env
10267816Ssteve.reinhardt@amd.com
102710454SCurtis.Dunham@arm.com        if static:
102810453SAndrew.Bardsley@arm.com            obj = env.StaticObject(source.tnode)
10294382Sbinkertn@umich.edu        else:
10304382Sbinkertn@umich.edu            obj = env.SharedObject(source.tnode)
10314382Sbinkertn@umich.edu
10324382Sbinkertn@umich.edu        if extra_deps:
10334382Sbinkertn@umich.edu            env.Depends(obj, extra_deps)
10344382Sbinkertn@umich.edu
10354382Sbinkertn@umich.edu        return obj
10364382Sbinkertn@umich.edu
103710196SCurtis.Dunham@arm.com    lib_guards = {'main': False, 'skip_lib': False}
10384382Sbinkertn@umich.edu
103910196SCurtis.Dunham@arm.com    # Without Python, leave out all Python content from the library
104010196SCurtis.Dunham@arm.com    # builds.  The option doesn't affect gem5 built as a program
104110196SCurtis.Dunham@arm.com    if GetOption('without_python'):
104210196SCurtis.Dunham@arm.com        lib_guards['skip_no_python'] = False
104310196SCurtis.Dunham@arm.com
104410196SCurtis.Dunham@arm.com    static_objs = []
104510196SCurtis.Dunham@arm.com    shared_objs = []
1046955SN/A    for s in guarded_source_iterator(Source.source_groups[None], **lib_guards):
10472655Sstever@eecs.umich.edu        static_objs.append(make_obj(s, True))
10482655Sstever@eecs.umich.edu        shared_objs.append(make_obj(s, False))
10492655Sstever@eecs.umich.edu
10502655Sstever@eecs.umich.edu    partial_objs = []
105110196SCurtis.Dunham@arm.com    for group, all_srcs in Source.source_groups.iteritems():
10525601Snate@binkert.org        # If these are the ungrouped source files, skip them.
10535601Snate@binkert.org        if not group:
105410196SCurtis.Dunham@arm.com            continue
105510196SCurtis.Dunham@arm.com
105610196SCurtis.Dunham@arm.com        # Get a list of the source files compatible with the current guards.
10575522Snate@binkert.org        srcs = [ s for s in guarded_source_iterator(all_srcs, **lib_guards) ]
10585863Snate@binkert.org        # If there aren't any left, skip this group.
10595601Snate@binkert.org        if not srcs:
10605601Snate@binkert.org            continue
10615601Snate@binkert.org
10625863Snate@binkert.org        # If partial linking is disabled, add these sources to the build
10639556Sandreas.hansson@arm.com        # directly, and short circuit this loop.
10649556Sandreas.hansson@arm.com        if disable_partial:
10659556Sandreas.hansson@arm.com            for s in srcs:
10669556Sandreas.hansson@arm.com                static_objs.append(make_obj(s, True))
10679556Sandreas.hansson@arm.com                shared_objs.append(make_obj(s, False))
10685559Snate@binkert.org            continue
10699556Sandreas.hansson@arm.com
10709618Ssteve.reinhardt@amd.com        # Set up the static partially linked objects.
10719618Ssteve.reinhardt@amd.com        source_objs = [ make_obj(s, True) for s in srcs ]
10729618Ssteve.reinhardt@amd.com        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
107310238Sandreas.hansson@arm.com        target = File(joinpath(group, file_name))
107410878Sandreas.hansson@arm.com        partial = env.PartialStatic(target=target, source=source_objs)
107511294Sandreas.hansson@arm.com        static_objs.append(partial)
107611294Sandreas.hansson@arm.com
107710457Sandreas.hansson@arm.com        # Set up the shared partially linked objects.
107810457Sandreas.hansson@arm.com        source_objs = [ make_obj(s, False) for s in srcs ]
107910457Sandreas.hansson@arm.com        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
108010457Sandreas.hansson@arm.com        target = File(joinpath(group, file_name))
108110457Sandreas.hansson@arm.com        partial = env.PartialShared(target=target, source=source_objs)
108210457Sandreas.hansson@arm.com        shared_objs.append(partial)
108310457Sandreas.hansson@arm.com
108410457Sandreas.hansson@arm.com    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
108510457Sandreas.hansson@arm.com    static_objs.append(static_date)
10868737Skoansin.tan@gmail.com
108711294Sandreas.hansson@arm.com    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
108811294Sandreas.hansson@arm.com    shared_objs.append(shared_date)
108911294Sandreas.hansson@arm.com
109010278SAndreas.Sandberg@ARM.com    # First make a library of everything but main() so other programs can
109110457Sandreas.hansson@arm.com    # link against m5.
109210457Sandreas.hansson@arm.com    static_lib = new_env.StaticLibrary(libname, static_objs)
109310457Sandreas.hansson@arm.com    shared_lib = new_env.SharedLibrary(libname, shared_objs)
109410457Sandreas.hansson@arm.com
109510457Sandreas.hansson@arm.com    # Now link a stub with main() and the static library.
109610457Sandreas.hansson@arm.com    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
10978945Ssteve.reinhardt@amd.com
109810686SAndreas.Sandberg@ARM.com    for test in UnitTest.all:
109910686SAndreas.Sandberg@ARM.com        flags = { test.target : True }
110010686SAndreas.Sandberg@ARM.com        test_sources = Source.get(**flags)
110110686SAndreas.Sandberg@ARM.com        test_objs = [ make_obj(s, static=True) for s in test_sources ]
110210686SAndreas.Sandberg@ARM.com        if test.main:
110310686SAndreas.Sandberg@ARM.com            test_objs += main_objs
11048945Ssteve.reinhardt@amd.com        path = variant('unittest/%s.%s' % (test.target, label))
11056143Snate@binkert.org        new_env.Program(path, test_objs + static_objs)
11066143Snate@binkert.org
11076143Snate@binkert.org    progname = exename
11086143Snate@binkert.org    if strip:
11096143Snate@binkert.org        progname += '.unstripped'
11106143Snate@binkert.org
11116143Snate@binkert.org    targets = new_env.Program(progname, main_objs + static_objs)
11128945Ssteve.reinhardt@amd.com
11138945Ssteve.reinhardt@amd.com    if strip:
11146143Snate@binkert.org        if sys.platform == 'sunos5':
11156143Snate@binkert.org            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
11166143Snate@binkert.org        else:
11176143Snate@binkert.org            cmd = 'strip $SOURCE -o $TARGET'
11186143Snate@binkert.org        targets = new_env.Command(exename, progname,
11196143Snate@binkert.org                    MakeAction(cmd, Transform("STRIP")))
11206143Snate@binkert.org
11216143Snate@binkert.org    new_env.Command(secondary_exename, exename,
11226143Snate@binkert.org            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
11236143Snate@binkert.org
11246143Snate@binkert.org    new_env.M5Binary = targets[0]
11256143Snate@binkert.org
11266143Snate@binkert.org    # Set up regression tests.
112710453SAndrew.Bardsley@arm.com    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
112810453SAndrew.Bardsley@arm.com               variant_dir=variantd('tests', new_env.Label),
112910453SAndrew.Bardsley@arm.com               exports={ 'env' : new_env }, duplicate=False)
113010453SAndrew.Bardsley@arm.com
113110453SAndrew.Bardsley@arm.com# Start out with the compiler flags common to all compilers,
113210453SAndrew.Bardsley@arm.com# i.e. they all use -g for opt and -g -pg for prof
113310453SAndrew.Bardsley@arm.comccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
113410453SAndrew.Bardsley@arm.com           'perf' : ['-g']}
113510453SAndrew.Bardsley@arm.com
11366143Snate@binkert.org# Start out with the linker flags common to all linkers, i.e. -pg for
11376143Snate@binkert.org# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
11386143Snate@binkert.org# no-as-needed and as-needed as the binutils linker is too clever and
113910453SAndrew.Bardsley@arm.com# simply doesn't link to the library otherwise.
11406143Snate@binkert.orgldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
11416240Snate@binkert.org           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
11425554Snate@binkert.org
11435522Snate@binkert.org# For Link Time Optimization, the optimisation flags used to compile
11445522Snate@binkert.org# individual files are decoupled from those used at link time
11455797Snate@binkert.org# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
11465797Snate@binkert.org# to also update the linker flags based on the target.
11475522Snate@binkert.orgif env['GCC']:
11485601Snate@binkert.org    if sys.platform == 'sunos5':
11498233Snate@binkert.org        ccflags['debug'] += ['-gstabs+']
11508233Snate@binkert.org    else:
11518235Snate@binkert.org        ccflags['debug'] += ['-ggdb3']
11528235Snate@binkert.org    ldflags['debug'] += ['-O0']
11538235Snate@binkert.org    # opt, fast, prof and perf all share the same cc flags, also add
11548235Snate@binkert.org    # the optimization to the ldflags as LTO defers the optimization
11559003SAli.Saidi@ARM.com    # to link time
11569003SAli.Saidi@ARM.com    for target in ['opt', 'fast', 'prof', 'perf']:
115710196SCurtis.Dunham@arm.com        ccflags[target] += ['-O3']
115810196SCurtis.Dunham@arm.com        ldflags[target] += ['-O3']
11598235Snate@binkert.org
11606143Snate@binkert.org    ccflags['fast'] += env['LTO_CCFLAGS']
11612655Sstever@eecs.umich.edu    ldflags['fast'] += env['LTO_LDFLAGS']
11626143Snate@binkert.orgelif env['CLANG']:
11636143Snate@binkert.org    ccflags['debug'] += ['-g', '-O0']
11648233Snate@binkert.org    # opt, fast, prof and perf all share the same cc flags
11656143Snate@binkert.org    for target in ['opt', 'fast', 'prof', 'perf']:
11666143Snate@binkert.org        ccflags[target] += ['-O3']
11674007Ssaidi@eecs.umich.eduelse:
11684596Sbinkertn@umich.edu    print 'Unknown compiler, please fix compiler options'
11694007Ssaidi@eecs.umich.edu    Exit(1)
11704596Sbinkertn@umich.edu
11717756SAli.Saidi@ARM.com
11727816Ssteve.reinhardt@amd.com# To speed things up, we only instantiate the build environments we
11738334Snate@binkert.org# need.  We try to identify the needed environment for each target; if
11748334Snate@binkert.org# we can't, we fall back on instantiating all the environments just to
11758334Snate@binkert.org# be safe.
11768334Snate@binkert.orgtarget_types = ['debug', 'opt', 'fast', 'prof', 'perf']
11775601Snate@binkert.orgobj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
117810196SCurtis.Dunham@arm.com              'gpo' : 'perf'}
11792655Sstever@eecs.umich.edu
11809225Sandreas.hansson@arm.comdef identifyTarget(t):
11819225Sandreas.hansson@arm.com    ext = t.split('.')[-1]
11829226Sandreas.hansson@arm.com    if ext in target_types:
11839226Sandreas.hansson@arm.com        return ext
11849225Sandreas.hansson@arm.com    if obj2target.has_key(ext):
11859226Sandreas.hansson@arm.com        return obj2target[ext]
11869226Sandreas.hansson@arm.com    match = re.search(r'/tests/([^/]+)/', t)
11879226Sandreas.hansson@arm.com    if match and match.group(1) in target_types:
11889226Sandreas.hansson@arm.com        return match.group(1)
11899226Sandreas.hansson@arm.com    return 'all'
11909226Sandreas.hansson@arm.com
11919225Sandreas.hansson@arm.comneeded_envs = [identifyTarget(target) for target in BUILD_TARGETS]
11929227Sandreas.hansson@arm.comif 'all' in needed_envs:
11939227Sandreas.hansson@arm.com    needed_envs += target_types
11949227Sandreas.hansson@arm.com
11959227Sandreas.hansson@arm.comdef makeEnvirons(target, source, env):
11968946Sandreas.hansson@arm.com    # cause any later Source() calls to be fatal, as a diagnostic.
11973918Ssaidi@eecs.umich.edu    Source.done()
11989225Sandreas.hansson@arm.com
11993918Ssaidi@eecs.umich.edu    # Debug binary
12009225Sandreas.hansson@arm.com    if 'debug' in needed_envs:
12019225Sandreas.hansson@arm.com        makeEnv(env, 'debug', '.do',
12029227Sandreas.hansson@arm.com                CCFLAGS = Split(ccflags['debug']),
12039227Sandreas.hansson@arm.com                CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
12049227Sandreas.hansson@arm.com                LINKFLAGS = Split(ldflags['debug']))
12059226Sandreas.hansson@arm.com
12069225Sandreas.hansson@arm.com    # Optimized binary
12079227Sandreas.hansson@arm.com    if 'opt' in needed_envs:
12089227Sandreas.hansson@arm.com        makeEnv(env, 'opt', '.o',
12099227Sandreas.hansson@arm.com                CCFLAGS = Split(ccflags['opt']),
12109227Sandreas.hansson@arm.com                CPPDEFINES = ['TRACING_ON=1'],
12118946Sandreas.hansson@arm.com                LINKFLAGS = Split(ldflags['opt']))
12129225Sandreas.hansson@arm.com
12139226Sandreas.hansson@arm.com    # "Fast" binary
12149226Sandreas.hansson@arm.com    if 'fast' in needed_envs:
12159226Sandreas.hansson@arm.com        disable_partial = \
12163515Ssaidi@eecs.umich.edu                env.get('BROKEN_INCREMENTAL_LTO', False) and \
12173918Ssaidi@eecs.umich.edu                GetOption('force_lto')
12184762Snate@binkert.org        makeEnv(env, 'fast', '.fo', strip = True,
12193515Ssaidi@eecs.umich.edu                CCFLAGS = Split(ccflags['fast']),
12208881Smarc.orr@gmail.com                CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
12218881Smarc.orr@gmail.com                LINKFLAGS = Split(ldflags['fast']),
12228881Smarc.orr@gmail.com                disable_partial=disable_partial)
12238881Smarc.orr@gmail.com
12248881Smarc.orr@gmail.com    # Profiled binary using gprof
12259226Sandreas.hansson@arm.com    if 'prof' in needed_envs:
12269226Sandreas.hansson@arm.com        makeEnv(env, 'prof', '.po',
12279226Sandreas.hansson@arm.com                CCFLAGS = Split(ccflags['prof']),
12288881Smarc.orr@gmail.com                CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
12298881Smarc.orr@gmail.com                LINKFLAGS = Split(ldflags['prof']))
12308881Smarc.orr@gmail.com
12318881Smarc.orr@gmail.com    # Profiled binary using google-pprof
12328881Smarc.orr@gmail.com    if 'perf' in needed_envs:
12338881Smarc.orr@gmail.com        makeEnv(env, 'perf', '.gpo',
12348881Smarc.orr@gmail.com                CCFLAGS = Split(ccflags['perf']),
12358881Smarc.orr@gmail.com                CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
12368881Smarc.orr@gmail.com                LINKFLAGS = Split(ldflags['perf']))
12378881Smarc.orr@gmail.com
12388881Smarc.orr@gmail.com# The MakeEnvirons Builder defers the full dependency collection until
12398881Smarc.orr@gmail.com# after processing the ISA definition (due to dynamically generated
12408881Smarc.orr@gmail.com# source files).  Add this dependency to all targets so they will wait
12418881Smarc.orr@gmail.com# until the environments are completely set up.  Otherwise, a second
12428881Smarc.orr@gmail.com# process (e.g. -j2 or higher) will try to compile the requested target,
12438881Smarc.orr@gmail.com# not know how, and fail.
124410196SCurtis.Dunham@arm.comenv.Append(BUILDERS = {'MakeEnvirons' :
124510196SCurtis.Dunham@arm.com                        Builder(action=MakeAction(makeEnvirons,
124610196SCurtis.Dunham@arm.com                                                  Transform("ENVIRONS", 1)))})
124710196SCurtis.Dunham@arm.com
1248955SN/Aisa_target = '#${VARIANT_NAME}-deps'
124910196SCurtis.Dunham@arm.comenvirons = '#${VARIANT_NAME}-environs'
1250955SN/Aenv.Depends('#all-deps', isa_target)
125110196SCurtis.Dunham@arm.comenv.Depends('#all-environs', environs)
125210196SCurtis.Dunham@arm.comenv.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
125310196SCurtis.Dunham@arm.comenvSetup = env.MakeEnvirons(environs, isa_target)
125410196SCurtis.Dunham@arm.com
125510196SCurtis.Dunham@arm.com# make sure no -deps targets occur before all ISAs are complete
125610196SCurtis.Dunham@arm.comenv.Depends(isa_target, '#all-isas')
125710196SCurtis.Dunham@arm.com# likewise for -environs targets and all the -deps targets
1258955SN/Aenv.Depends(environs, '#all-deps')
125910196SCurtis.Dunham@arm.com