SConscript revision 13576
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2018 ARM Limited
4955SN/A#
5955SN/A# The license below extends only to copyright in the software and shall
6955SN/A# not be construed as granting a license to any other intellectual
7955SN/A# property including but not limited to intellectual property relating
8955SN/A# to a hardware implementation of the functionality of the software
9955SN/A# licensed hereunder.  You may use the software subject to the license
10955SN/A# terms below provided that you ensure that this notice is replicated
11955SN/A# unmodified and in its entirety in all distributions of the software,
12955SN/A# modified or unmodified, in source code or in binary form.
13955SN/A#
14955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
15955SN/A# All rights reserved.
16955SN/A#
17955SN/A# Redistribution and use in source and binary forms, with or without
18955SN/A# modification, are permitted provided that the following conditions are
19955SN/A# met: redistributions of source code must retain the above copyright
20955SN/A# notice, this list of conditions and the following disclaimer;
21955SN/A# redistributions in binary form must reproduce the above copyright
22955SN/A# notice, this list of conditions and the following disclaimer in the
23955SN/A# documentation and/or other materials provided with the distribution;
24955SN/A# neither the name of the copyright holders nor the names of its
25955SN/A# contributors may be used to endorse or promote products derived from
26955SN/A# this software without specific prior written permission.
27955SN/A#
282665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
294762Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
315522Snate@binkert.org# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
324762Snate@binkert.org# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
335522Snate@binkert.org# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
355522Snate@binkert.org# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
375522Snate@binkert.org# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
384202Sbinkertn@umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
395742Snate@binkert.org#
40955SN/A# Authors: Nathan Binkert
414381Sbinkertn@umich.edu
424381Sbinkertn@umich.edufrom __future__ import print_function
43955SN/A
44955SN/Aimport array
45955SN/Aimport bisect
464202Sbinkertn@umich.eduimport functools
47955SN/Aimport imp
484382Sbinkertn@umich.eduimport marshal
494382Sbinkertn@umich.eduimport os
504382Sbinkertn@umich.eduimport re
515517Snate@binkert.orgimport subprocess
525517Snate@binkert.orgimport sys
534762Snate@binkert.orgimport zlib
544762Snate@binkert.org
554762Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
564762Snate@binkert.org
574762Snate@binkert.orgimport SCons
584762Snate@binkert.org
594762Snate@binkert.orgfrom gem5_scons import Transform
604762Snate@binkert.org
614762Snate@binkert.org# This file defines how to build a particular configuration of gem5
624762Snate@binkert.org# based on variable settings in the 'env' build environment.
635522Snate@binkert.org
645604Snate@binkert.orgImport('*')
655604Snate@binkert.org
665604Snate@binkert.org# Children need to see the environment
674762Snate@binkert.orgExport('env')
684762Snate@binkert.org
694762Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
705522Snate@binkert.org
715522Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
725522Snate@binkert.org
735522Snate@binkert.org########################################################################
745604Snate@binkert.org# Code for adding source files of various types
755604Snate@binkert.org#
764762Snate@binkert.org# When specifying a source file of some type, a set of tags can be
774762Snate@binkert.org# specified for that file.
784762Snate@binkert.org
794762Snate@binkert.orgclass SourceFilter(object):
805522Snate@binkert.org    def __init__(self, predicate):
814762Snate@binkert.org        self.predicate = predicate
824762Snate@binkert.org
835604Snate@binkert.org    def __or__(self, other):
845604Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) or
855604Snate@binkert.org                                         other.predicate(tags))
865604Snate@binkert.org
875604Snate@binkert.org    def __and__(self, other):
885604Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) and
894762Snate@binkert.org                                         other.predicate(tags))
904762Snate@binkert.org
914762Snate@binkert.orgdef with_tags_that(predicate):
924762Snate@binkert.org    '''Return a list of sources with tags that satisfy a predicate.'''
935604Snate@binkert.org    return SourceFilter(predicate)
944762Snate@binkert.org
955522Snate@binkert.orgdef with_any_tags(*tags):
965522Snate@binkert.org    '''Return a list of sources with any of the supplied tags.'''
975522Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) > 0)
984762Snate@binkert.org
994382Sbinkertn@umich.edudef with_all_tags(*tags):
1004762Snate@binkert.org    '''Return a list of sources with all of the supplied tags.'''
1014382Sbinkertn@umich.edu    return SourceFilter(lambda stags: set(tags) <= stags)
1025522Snate@binkert.org
1034381Sbinkertn@umich.edudef with_tag(tag):
1045522Snate@binkert.org    '''Return a list of sources with the supplied tag.'''
1054762Snate@binkert.org    return SourceFilter(lambda stags: tag in stags)
1064762Snate@binkert.org
1074762Snate@binkert.orgdef without_tags(*tags):
1085522Snate@binkert.org    '''Return a list of sources without any of the supplied tags.'''
1095522Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) == 0)
1105522Snate@binkert.org
1115522Snate@binkert.orgdef without_tag(tag):
1125522Snate@binkert.org    '''Return a list of sources with the supplied tag.'''
1135522Snate@binkert.org    return SourceFilter(lambda stags: tag not in stags)
1145522Snate@binkert.org
1155522Snate@binkert.orgsource_filter_factories = {
1165522Snate@binkert.org    'with_tags_that': with_tags_that,
1174762Snate@binkert.org    'with_any_tags': with_any_tags,
1184762Snate@binkert.org    'with_all_tags': with_all_tags,
1194762Snate@binkert.org    'with_tag': with_tag,
1204762Snate@binkert.org    'without_tags': without_tags,
1214762Snate@binkert.org    'without_tag': without_tag,
1224762Snate@binkert.org}
1234762Snate@binkert.org
1244762Snate@binkert.orgExport(source_filter_factories)
1254762Snate@binkert.org
1264762Snate@binkert.orgclass SourceList(list):
1274762Snate@binkert.org    def apply_filter(self, f):
1284762Snate@binkert.org        def match(source):
1294762Snate@binkert.org            return f.predicate(source.tags)
1304762Snate@binkert.org        return SourceList(filter(match, self))
1314762Snate@binkert.org
1324762Snate@binkert.org    def __getattr__(self, name):
1334762Snate@binkert.org        func = source_filter_factories.get(name, None)
1344762Snate@binkert.org        if not func:
1354762Snate@binkert.org            raise AttributeError
1364762Snate@binkert.org
1374762Snate@binkert.org        @functools.wraps(func)
1384762Snate@binkert.org        def wrapper(*args, **kwargs):
1394762Snate@binkert.org            return self.apply_filter(func(*args, **kwargs))
1404762Snate@binkert.org        return wrapper
1414762Snate@binkert.org
1424762Snate@binkert.orgclass SourceMeta(type):
1434762Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
1444762Snate@binkert.org    particular type.'''
1454762Snate@binkert.org    def __init__(cls, name, bases, dict):
1464762Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
1474762Snate@binkert.org        cls.all = SourceList()
1484762Snate@binkert.org
1494762Snate@binkert.orgclass SourceFile(object):
1504762Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1514762Snate@binkert.org    This includes, the source node, target node, various manipulations
152955SN/A    of those.  A source file also specifies a set of tags which
1535584Snate@binkert.org    describing arbitrary properties of the source file.'''
1545584Snate@binkert.org    __metaclass__ = SourceMeta
1555584Snate@binkert.org
1565584Snate@binkert.org    static_objs = {}
1575584Snate@binkert.org    shared_objs = {}
1585584Snate@binkert.org
1595584Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
1605584Snate@binkert.org        if tags is None:
1615584Snate@binkert.org            tags='gem5 lib'
1625584Snate@binkert.org        if isinstance(tags, basestring):
1635584Snate@binkert.org            tags = set([tags])
1645584Snate@binkert.org        if not isinstance(tags, set):
1655584Snate@binkert.org            tags = set(tags)
1664382Sbinkertn@umich.edu        self.tags = tags
1674202Sbinkertn@umich.edu
1685522Snate@binkert.org        if add_tags:
1694382Sbinkertn@umich.edu            if isinstance(add_tags, basestring):
1704382Sbinkertn@umich.edu                add_tags = set([add_tags])
1714382Sbinkertn@umich.edu            if not isinstance(add_tags, set):
1725584Snate@binkert.org                add_tags = set(add_tags)
1734382Sbinkertn@umich.edu            self.tags |= add_tags
1744382Sbinkertn@umich.edu
1754382Sbinkertn@umich.edu        tnode = source
1765192Ssaidi@eecs.umich.edu        if not isinstance(source, SCons.Node.FS.File):
1775192Ssaidi@eecs.umich.edu            tnode = File(source)
1785192Ssaidi@eecs.umich.edu
1795192Ssaidi@eecs.umich.edu        self.tnode = tnode
1805192Ssaidi@eecs.umich.edu        self.snode = tnode.srcnode()
1815192Ssaidi@eecs.umich.edu
1825192Ssaidi@eecs.umich.edu        for base in type(self).__mro__:
1835192Ssaidi@eecs.umich.edu            if issubclass(base, SourceFile):
1845192Ssaidi@eecs.umich.edu                base.all.append(self)
1855192Ssaidi@eecs.umich.edu
1865192Ssaidi@eecs.umich.edu    def static(self, env):
1875192Ssaidi@eecs.umich.edu        key = (self.tnode, env['OBJSUFFIX'])
1885192Ssaidi@eecs.umich.edu        if not key in self.static_objs:
1895192Ssaidi@eecs.umich.edu            self.static_objs[key] = env.StaticObject(self.tnode)
1905192Ssaidi@eecs.umich.edu        return self.static_objs[key]
1915192Ssaidi@eecs.umich.edu
1925192Ssaidi@eecs.umich.edu    def shared(self, env):
1935192Ssaidi@eecs.umich.edu        key = (self.tnode, env['OBJSUFFIX'])
1945192Ssaidi@eecs.umich.edu        if not key in self.shared_objs:
1955192Ssaidi@eecs.umich.edu            self.shared_objs[key] = env.SharedObject(self.tnode)
1965192Ssaidi@eecs.umich.edu        return self.shared_objs[key]
1975192Ssaidi@eecs.umich.edu
1985192Ssaidi@eecs.umich.edu    @property
1995192Ssaidi@eecs.umich.edu    def filename(self):
2005192Ssaidi@eecs.umich.edu        return str(self.tnode)
2015192Ssaidi@eecs.umich.edu
2025192Ssaidi@eecs.umich.edu    @property
2035192Ssaidi@eecs.umich.edu    def dirname(self):
2045192Ssaidi@eecs.umich.edu        return dirname(self.filename)
2055192Ssaidi@eecs.umich.edu
2065192Ssaidi@eecs.umich.edu    @property
2075192Ssaidi@eecs.umich.edu    def basename(self):
2084382Sbinkertn@umich.edu        return basename(self.filename)
2094382Sbinkertn@umich.edu
2104382Sbinkertn@umich.edu    @property
2112667Sstever@eecs.umich.edu    def extname(self):
2122667Sstever@eecs.umich.edu        index = self.basename.rfind('.')
2132667Sstever@eecs.umich.edu        if index <= 0:
2142667Sstever@eecs.umich.edu            # dot files aren't extensions
2152667Sstever@eecs.umich.edu            return self.basename, None
2162667Sstever@eecs.umich.edu
2175742Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
2185742Snate@binkert.org
2195742Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
2202037SN/A    def __le__(self, other): return self.filename <= other.filename
2212037SN/A    def __gt__(self, other): return self.filename > other.filename
2222037SN/A    def __ge__(self, other): return self.filename >= other.filename
2235793Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
2245793Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
2255793Snate@binkert.org
2265793Snate@binkert.orgdef blobToCpp(data, symbol, cpp_code, hpp_code=None, namespace=None):
2275793Snate@binkert.org    '''
2284382Sbinkertn@umich.edu    Convert bytes data into C++ .cpp and .hh uint8_t byte array
2294762Snate@binkert.org    code containing that binary data.
2305344Sstever@gmail.com
2314382Sbinkertn@umich.edu    :param data: binary data to be converted to C++
2325341Sstever@gmail.com    :param symbol: name of the symbol
2335742Snate@binkert.org    :param cpp_code: append the generated cpp_code to this object
2345742Snate@binkert.org    :param hpp_code: append the generated hpp_code to this object
2355742Snate@binkert.org                     If None, ignore it. Otherwise, also include it
2365742Snate@binkert.org                     in the .cpp file.
2375742Snate@binkert.org    :param namespace: namespace to put the symbol into. If None,
2384762Snate@binkert.org                      don't put the symbols into any namespace.
2395742Snate@binkert.org    '''
2405742Snate@binkert.org    symbol_len_declaration = 'const std::size_t {}_len'.format(symbol)
2415742Snate@binkert.org    symbol_declaration = 'const std::uint8_t {}[]'.format(symbol)
2425742Snate@binkert.org    if hpp_code is not None:
2435742Snate@binkert.org        cpp_code('''\
2445742Snate@binkert.org#include "blobs/{}.hh"
2455742Snate@binkert.org'''.format(symbol))
2465341Sstever@gmail.com        hpp_code('''\
2475742Snate@binkert.org#include <cstddef>
2485341Sstever@gmail.com#include <cstdint>
2494773Snate@binkert.org''')
2501858SN/A        if namespace is not None:
2511858SN/A            hpp_code('namespace {} {{'.format(namespace))
2521085SN/A        hpp_code('extern ' + symbol_len_declaration + ';')
2534382Sbinkertn@umich.edu        hpp_code('extern ' + symbol_declaration + ';')
2544382Sbinkertn@umich.edu        if namespace is not None:
2554762Snate@binkert.org            hpp_code('}')
2564762Snate@binkert.org    if namespace is not None:
2574762Snate@binkert.org        cpp_code('namespace {} {{'.format(namespace))
2585517Snate@binkert.org    cpp_code(symbol_len_declaration + ' = {};'.format(len(data)))
2595517Snate@binkert.org    cpp_code(symbol_declaration + ' = {')
2605517Snate@binkert.org    cpp_code.indent()
2615517Snate@binkert.org    step = 16
2625517Snate@binkert.org    for i in xrange(0, len(data), step):
2635517Snate@binkert.org        x = array.array('B', data[i:i+step])
2645517Snate@binkert.org        cpp_code(''.join('%d,' % d for d in x))
2655517Snate@binkert.org    cpp_code.dedent()
2665517Snate@binkert.org    cpp_code('};')
2675517Snate@binkert.org    if namespace is not None:
2685517Snate@binkert.org        cpp_code('}')
2695517Snate@binkert.org
2705517Snate@binkert.orgdef Blob(blob_path, symbol):
2715517Snate@binkert.org    '''
2725517Snate@binkert.org    Embed an arbitrary blob into the gem5 executable,
2735517Snate@binkert.org    and make it accessible to C++ as a byte array.
2745517Snate@binkert.org    '''
2755517Snate@binkert.org    blob_path = os.path.abspath(blob_path)
2765517Snate@binkert.org    blob_out_dir = os.path.join(env['BUILDDIR'], 'blobs')
2775517Snate@binkert.org    path_noext = joinpath(blob_out_dir, symbol)
2785517Snate@binkert.org    cpp_path = path_noext + '.cc'
2795517Snate@binkert.org    hpp_path = path_noext + '.hh'
2805517Snate@binkert.org    def embedBlob(target, source, env):
2815517Snate@binkert.org        data = file(str(source[0]), 'r').read()
2825517Snate@binkert.org        cpp_code = code_formatter()
2835517Snate@binkert.org        hpp_code = code_formatter()
2845517Snate@binkert.org        blobToCpp(data, symbol, cpp_code, hpp_code, namespace='Blobs')
2855517Snate@binkert.org        cpp_path = str(target[0])
2865517Snate@binkert.org        hpp_path = str(target[1])
2875517Snate@binkert.org        cpp_dir = os.path.split(cpp_path)[0]
2885517Snate@binkert.org        if not os.path.exists(cpp_dir):
2895517Snate@binkert.org            os.makedirs(cpp_dir)
2905517Snate@binkert.org        cpp_code.write(cpp_path)
2915517Snate@binkert.org        hpp_code.write(hpp_path)
2925517Snate@binkert.org    env.Command([cpp_path, hpp_path], blob_path,
2935517Snate@binkert.org                MakeAction(embedBlob, Transform("EMBED BLOB")))
2945517Snate@binkert.org    Source(cpp_path)
2955517Snate@binkert.org
2965517Snate@binkert.orgclass Source(SourceFile):
2975517Snate@binkert.org    ungrouped_tag = 'No link group'
2985517Snate@binkert.org    source_groups = set()
2995517Snate@binkert.org
3005517Snate@binkert.org    _current_group_tag = ungrouped_tag
3015517Snate@binkert.org
3025517Snate@binkert.org    @staticmethod
3035517Snate@binkert.org    def link_group_tag(group):
3045517Snate@binkert.org        return 'link group: %s' % group
3055517Snate@binkert.org
3065517Snate@binkert.org    @classmethod
3075517Snate@binkert.org    def set_group(cls, group):
3085517Snate@binkert.org        new_tag = Source.link_group_tag(group)
3095517Snate@binkert.org        Source._current_group_tag = new_tag
3105517Snate@binkert.org        Source.source_groups.add(group)
3115517Snate@binkert.org
3125517Snate@binkert.org    def _add_link_group_tag(self):
3135517Snate@binkert.org        self.tags.add(Source._current_group_tag)
3145522Snate@binkert.org
3155517Snate@binkert.org    '''Add a c/c++ source file to the build'''
3165517Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3175517Snate@binkert.org        '''specify the source file, and any tags'''
3185517Snate@binkert.org        super(Source, self).__init__(source, tags, add_tags)
3194762Snate@binkert.org        self._add_link_group_tag()
3205517Snate@binkert.org
3215517Snate@binkert.orgclass PySource(SourceFile):
3224762Snate@binkert.org    '''Add a python source file to the named package'''
3235517Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
3244762Snate@binkert.org    modules = {}
3255517Snate@binkert.org    tnodes = {}
3265517Snate@binkert.org    symnames = {}
3275517Snate@binkert.org
3285517Snate@binkert.org    def __init__(self, package, source, tags=None, add_tags=None):
3295517Snate@binkert.org        '''specify the python package, the source file, and any tags'''
3305517Snate@binkert.org        super(PySource, self).__init__(source, tags, add_tags)
3315517Snate@binkert.org
3325517Snate@binkert.org        modname,ext = self.extname
3335517Snate@binkert.org        assert ext == 'py'
3345517Snate@binkert.org
3355517Snate@binkert.org        if package:
3365517Snate@binkert.org            path = package.split('.')
3375517Snate@binkert.org        else:
3385517Snate@binkert.org            path = []
3395517Snate@binkert.org
3405517Snate@binkert.org        modpath = path[:]
3415517Snate@binkert.org        if modname != '__init__':
3425517Snate@binkert.org            modpath += [ modname ]
3435517Snate@binkert.org        modpath = '.'.join(modpath)
3445517Snate@binkert.org
3455517Snate@binkert.org        arcpath = path + [ self.basename ]
3465517Snate@binkert.org        abspath = self.snode.abspath
3475517Snate@binkert.org        if not exists(abspath):
3484762Snate@binkert.org            abspath = self.tnode.abspath
3494762Snate@binkert.org
3504762Snate@binkert.org        self.package = package
3514762Snate@binkert.org        self.modname = modname
3524762Snate@binkert.org        self.modpath = modpath
3534762Snate@binkert.org        self.arcname = joinpath(*arcpath)
3545517Snate@binkert.org        self.abspath = abspath
3554762Snate@binkert.org        self.compiled = File(self.filename + 'c')
3564762Snate@binkert.org        self.cpp = File(self.filename + '.cc')
3574762Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
3584762Snate@binkert.org
3594382Sbinkertn@umich.edu        PySource.modules[modpath] = self
3604382Sbinkertn@umich.edu        PySource.tnodes[self.tnode] = self
3615517Snate@binkert.org        PySource.symnames[self.symname] = self
3625517Snate@binkert.org
3635517Snate@binkert.orgclass SimObject(PySource):
3645517Snate@binkert.org    '''Add a SimObject python file as a python source object and add
3655517Snate@binkert.org    it to a list of sim object modules'''
3665517Snate@binkert.org
3675517Snate@binkert.org    fixed = False
3685517Snate@binkert.org    modnames = []
3695517Snate@binkert.org
3705517Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3715517Snate@binkert.org        '''Specify the source file and any tags (automatically in
3725517Snate@binkert.org        the m5.objects package)'''
3735517Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)
3745517Snate@binkert.org        if self.fixed:
3755517Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
3765517Snate@binkert.org
3775517Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
3785517Snate@binkert.org
3795517Snate@binkert.orgclass ProtoBuf(SourceFile):
3805517Snate@binkert.org    '''Add a Protocol Buffer to build'''
3815517Snate@binkert.org
3825517Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3835517Snate@binkert.org        '''Specify the source file, and any tags'''
3845517Snate@binkert.org        super(ProtoBuf, self).__init__(source, tags, add_tags)
3854762Snate@binkert.org
3865517Snate@binkert.org        # Get the file name and the extension
3874382Sbinkertn@umich.edu        modname,ext = self.extname
3884382Sbinkertn@umich.edu        assert ext == 'proto'
3894762Snate@binkert.org
3904382Sbinkertn@umich.edu        # Currently, we stick to generating the C++ headers, so we
3914382Sbinkertn@umich.edu        # only need to track the source and header.
3925517Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
3934382Sbinkertn@umich.edu        self.hh_file = File(modname + '.pb.h')
3944382Sbinkertn@umich.edu
3954762Snate@binkert.org
3964382Sbinkertn@umich.eduexectuable_classes = []
3974762Snate@binkert.orgclass ExecutableMeta(type):
3985517Snate@binkert.org    '''Meta class for Executables.'''
3994382Sbinkertn@umich.edu    all = []
4004382Sbinkertn@umich.edu
4014762Snate@binkert.org    def __init__(cls, name, bases, d):
4024762Snate@binkert.org        if not d.pop('abstract', False):
4034762Snate@binkert.org            ExecutableMeta.all.append(cls)
4044762Snate@binkert.org        super(ExecutableMeta, cls).__init__(name, bases, d)
4054762Snate@binkert.org
4065517Snate@binkert.org        cls.all = []
4075517Snate@binkert.org
4085517Snate@binkert.orgclass Executable(object):
4095517Snate@binkert.org    '''Base class for creating an executable from sources.'''
4105517Snate@binkert.org    __metaclass__ = ExecutableMeta
4115517Snate@binkert.org
4125517Snate@binkert.org    abstract = True
4135517Snate@binkert.org
4145517Snate@binkert.org    def __init__(self, target, *srcs_and_filts):
4155517Snate@binkert.org        '''Specify the target name and any sources. Sources that are
4165517Snate@binkert.org        not SourceFiles are evalued with Source().'''
4175517Snate@binkert.org        super(Executable, self).__init__()
4185517Snate@binkert.org        self.all.append(self)
4195517Snate@binkert.org        self.target = target
4205517Snate@binkert.org
4215517Snate@binkert.org        isFilter = lambda arg: isinstance(arg, SourceFilter)
4225517Snate@binkert.org        self.filters = filter(isFilter, srcs_and_filts)
4235517Snate@binkert.org        sources = filter(lambda a: not isFilter(a), srcs_and_filts)
4245517Snate@binkert.org
4255517Snate@binkert.org        srcs = SourceList()
4265517Snate@binkert.org        for src in sources:
4275517Snate@binkert.org            if not isinstance(src, SourceFile):
4285517Snate@binkert.org                src = Source(src, tags=[])
4295517Snate@binkert.org            srcs.append(src)
4305517Snate@binkert.org
4315517Snate@binkert.org        self.sources = srcs
4325517Snate@binkert.org        self.dir = Dir('.')
4335517Snate@binkert.org
4345517Snate@binkert.org    def path(self, env):
4355517Snate@binkert.org        return self.dir.File(self.target + '.' + env['EXE_SUFFIX'])
4365517Snate@binkert.org
4375517Snate@binkert.org    def srcs_to_objs(self, env, sources):
4385517Snate@binkert.org        return list([ s.static(env) for s in sources ])
4395517Snate@binkert.org
4405517Snate@binkert.org    @classmethod
4415517Snate@binkert.org    def declare_all(cls, env):
4425517Snate@binkert.org        return list([ instance.declare(env) for instance in cls.all ])
4435517Snate@binkert.org
4444762Snate@binkert.org    def declare(self, env, objs=None):
4454762Snate@binkert.org        if objs is None:
4465517Snate@binkert.org            objs = self.srcs_to_objs(env, self.sources)
4475517Snate@binkert.org
4484762Snate@binkert.org        if env['STRIP_EXES']:
4494762Snate@binkert.org            stripped = self.path(env)
4504762Snate@binkert.org            unstripped = env.File(str(stripped) + '.unstripped')
4515517Snate@binkert.org            if sys.platform == 'sunos5':
4524762Snate@binkert.org                cmd = 'cp $SOURCE $TARGET; strip $TARGET'
4534762Snate@binkert.org            else:
4544762Snate@binkert.org                cmd = 'strip $SOURCE -o $TARGET'
4555463Snate@binkert.org            env.Program(unstripped, objs)
4565517Snate@binkert.org            return env.Command(stripped, unstripped,
4574762Snate@binkert.org                               MakeAction(cmd, Transform("STRIP")))
4584762Snate@binkert.org        else:
4594762Snate@binkert.org            return env.Program(self.path(env), objs)
4604762Snate@binkert.org
4614762Snate@binkert.orgclass UnitTest(Executable):
4624762Snate@binkert.org    '''Create a UnitTest'''
4635463Snate@binkert.org    def __init__(self, target, *srcs_and_filts, **kwargs):
4645517Snate@binkert.org        super(UnitTest, self).__init__(target, *srcs_and_filts)
4654762Snate@binkert.org
4664762Snate@binkert.org        self.main = kwargs.get('main', False)
4674762Snate@binkert.org
4685517Snate@binkert.org    def declare(self, env):
4695517Snate@binkert.org        sources = list(self.sources)
4704762Snate@binkert.org        for f in self.filters:
4714762Snate@binkert.org            sources = Source.all.apply_filter(f)
4725517Snate@binkert.org        objs = self.srcs_to_objs(env, sources) + env['STATIC_OBJS']
4734762Snate@binkert.org        if self.main:
4744762Snate@binkert.org            objs += env['MAIN_OBJS']
4754762Snate@binkert.org        return super(UnitTest, self).declare(env, objs)
4764762Snate@binkert.org
4775517Snate@binkert.orgclass GTest(Executable):
4784762Snate@binkert.org    '''Create a unit test based on the google test framework.'''
4794762Snate@binkert.org    all = []
4804762Snate@binkert.org    def __init__(self, *srcs_and_filts, **kwargs):
4814762Snate@binkert.org        super(GTest, self).__init__(*srcs_and_filts)
4825517Snate@binkert.org
4835517Snate@binkert.org        self.skip_lib = kwargs.pop('skip_lib', False)
4845517Snate@binkert.org
4855517Snate@binkert.org    @classmethod
4865517Snate@binkert.org    def declare_all(cls, env):
4875517Snate@binkert.org        env = env.Clone()
4885517Snate@binkert.org        env.Append(LIBS=env['GTEST_LIBS'])
4895517Snate@binkert.org        env.Append(CPPFLAGS=env['GTEST_CPPFLAGS'])
4905517Snate@binkert.org        env['GTEST_LIB_SOURCES'] = Source.all.with_tag('gtest lib')
4915517Snate@binkert.org        env['GTEST_OUT_DIR'] = \
4925517Snate@binkert.org            Dir(env['BUILDDIR']).Dir('unittests.' + env['EXE_SUFFIX'])
4935517Snate@binkert.org        return super(GTest, cls).declare_all(env)
4945517Snate@binkert.org
4955517Snate@binkert.org    def declare(self, env):
4965517Snate@binkert.org        sources = list(self.sources)
4975517Snate@binkert.org        if not self.skip_lib:
4985517Snate@binkert.org            sources += env['GTEST_LIB_SOURCES']
4995517Snate@binkert.org        for f in self.filters:
5005517Snate@binkert.org            sources += Source.all.apply_filter(f)
5015517Snate@binkert.org        objs = self.srcs_to_objs(env, sources)
5025517Snate@binkert.org
5035517Snate@binkert.org        binary = super(GTest, self).declare(env, objs)
5045517Snate@binkert.org
5055517Snate@binkert.org        out_dir = env['GTEST_OUT_DIR']
5065517Snate@binkert.org        xml_file = out_dir.Dir(str(self.dir)).File(self.target + '.xml')
5075517Snate@binkert.org        AlwaysBuild(env.Command(xml_file, binary,
5085517Snate@binkert.org            "${SOURCES[0]} --gtest_output=xml:${TARGETS[0]}"))
5095517Snate@binkert.org
5105517Snate@binkert.org        return binary
5115517Snate@binkert.org
5125517Snate@binkert.orgclass Gem5(Executable):
5135517Snate@binkert.org    '''Create a gem5 executable.'''
5145517Snate@binkert.org
5155517Snate@binkert.org    def __init__(self, target):
5165517Snate@binkert.org        super(Gem5, self).__init__(target)
5175517Snate@binkert.org
5185517Snate@binkert.org    def declare(self, env):
5195517Snate@binkert.org        objs = env['MAIN_OBJS'] + env['STATIC_OBJS']
5205517Snate@binkert.org        return super(Gem5, self).declare(env, objs)
5215517Snate@binkert.org
5225517Snate@binkert.org
5235517Snate@binkert.org# Children should have access
5245517Snate@binkert.orgExport('Blob')
5255517Snate@binkert.orgExport('Source')
5265517Snate@binkert.orgExport('PySource')
5275517Snate@binkert.orgExport('SimObject')
5285517Snate@binkert.orgExport('ProtoBuf')
5295517Snate@binkert.orgExport('Executable')
5305517Snate@binkert.orgExport('UnitTest')
5315517Snate@binkert.orgExport('GTest')
5325517Snate@binkert.org
5335517Snate@binkert.org########################################################################
5345517Snate@binkert.org#
5355517Snate@binkert.org# Debug Flags
5365517Snate@binkert.org#
5375517Snate@binkert.orgdebug_flags = {}
5385517Snate@binkert.orgdef DebugFlag(name, desc=None):
5395517Snate@binkert.org    if name in debug_flags:
5405517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
5415517Snate@binkert.org    debug_flags[name] = (name, (), desc)
5425517Snate@binkert.org
5435517Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
5445517Snate@binkert.org    if name in debug_flags:
5455517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
5465517Snate@binkert.org
5475517Snate@binkert.org    compound = tuple(flags)
5485610Snate@binkert.org    debug_flags[name] = (name, compound, desc)
5495623Snate@binkert.org
5505623Snate@binkert.orgExport('DebugFlag')
5515623Snate@binkert.orgExport('CompoundFlag')
5525610Snate@binkert.org
5535517Snate@binkert.org########################################################################
5545623Snate@binkert.org#
5555623Snate@binkert.org# Set some compiler variables
5565623Snate@binkert.org#
5575623Snate@binkert.org
5585623Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
5595623Snate@binkert.org# automatically expand '.' to refer to both the source directory and
5605623Snate@binkert.org# the corresponding build directory to pick up generated include
5615517Snate@binkert.org# files.
5625610Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
5635610Snate@binkert.org
5645610Snate@binkert.orgfor extra_dir in extras_dir_list:
5655610Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
5665517Snate@binkert.org
5675517Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
5685610Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
5695610Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
5705517Snate@binkert.org    Dir(root[len(base_dir) + 1:])
5715517Snate@binkert.org
5725517Snate@binkert.org########################################################################
5735517Snate@binkert.org#
5745517Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
5755517Snate@binkert.org#
5765517Snate@binkert.org
5775517Snate@binkert.orghere = Dir('.').srcnode().abspath
5785517Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
5795517Snate@binkert.org    if root == here:
5804762Snate@binkert.org        # we don't want to recurse back into this SConscript
5815517Snate@binkert.org        continue
5825517Snate@binkert.org
5835463Snate@binkert.org    if 'SConscript' in files:
5844762Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
5854762Snate@binkert.org        Source.set_group(build_dir)
5864762Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
5874382Sbinkertn@umich.edu
5885554Snate@binkert.orgfor extra_dir in extras_dir_list:
5894762Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
5904382Sbinkertn@umich.edu
5914762Snate@binkert.org    # Also add the corresponding build directory to pick up generated
5924382Sbinkertn@umich.edu    # include files.
5934762Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
5944762Snate@binkert.org
5954762Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
5964762Snate@binkert.org        # if build lives in the extras directory, don't walk down it
5974382Sbinkertn@umich.edu        if 'build' in dirs:
5984382Sbinkertn@umich.edu            dirs.remove('build')
5994382Sbinkertn@umich.edu
6004382Sbinkertn@umich.edu        if 'SConscript' in files:
6014382Sbinkertn@umich.edu            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
6024382Sbinkertn@umich.edu            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
6034762Snate@binkert.org
6044382Sbinkertn@umich.edufor opt in export_vars:
6055554Snate@binkert.org    env.ConfigFile(opt)
6064382Sbinkertn@umich.edu
6074382Sbinkertn@umich.edudef makeTheISA(source, target, env):
6084762Snate@binkert.org    isas = [ src.get_contents() for src in source ]
6095517Snate@binkert.org    target_isa = env['TARGET_ISA']
6105517Snate@binkert.org    def define(isa):
6115517Snate@binkert.org        return isa.upper() + '_ISA'
6125517Snate@binkert.org
6135517Snate@binkert.org    def namespace(isa):
6145517Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
6155522Snate@binkert.org
6165517Snate@binkert.org
6175517Snate@binkert.org    code = code_formatter()
6185517Snate@binkert.org    code('''\
6195517Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
6205517Snate@binkert.org#define __CONFIG_THE_ISA_HH__
6215522Snate@binkert.org
6225522Snate@binkert.org''')
6234382Sbinkertn@umich.edu
6245192Ssaidi@eecs.umich.edu    # create defines for the preprocessing and compile-time determination
6255517Snate@binkert.org    for i,isa in enumerate(isas):
6265517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
6275517Snate@binkert.org    code()
6285517Snate@binkert.org
6295517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
6305517Snate@binkert.org    # reuse the same name as the namespaces
6315517Snate@binkert.org    code('enum class Arch {')
6325517Snate@binkert.org    for i,isa in enumerate(isas):
6335517Snate@binkert.org        if i + 1 == len(isas):
6345517Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
6355517Snate@binkert.org        else:
6365517Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
6375517Snate@binkert.org    code('};')
6385517Snate@binkert.org
6395517Snate@binkert.org    code('''
6405517Snate@binkert.org
6415517Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
6425517Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
6435517Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
6445517Snate@binkert.org
6455517Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
6465517Snate@binkert.org
6475517Snate@binkert.org    code.write(str(target[0]))
6485517Snate@binkert.org
6495517Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
6505517Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
6515517Snate@binkert.org
6525517Snate@binkert.orgdef makeTheGPUISA(source, target, env):
6535517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
6545517Snate@binkert.org    target_gpu_isa = env['TARGET_GPU_ISA']
6555517Snate@binkert.org    def define(isa):
6565517Snate@binkert.org        return isa.upper() + '_ISA'
6575517Snate@binkert.org
6585517Snate@binkert.org    def namespace(isa):
6595517Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
6605517Snate@binkert.org
6615517Snate@binkert.org
6625517Snate@binkert.org    code = code_formatter()
6635517Snate@binkert.org    code('''\
6645517Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
6655517Snate@binkert.org#define __CONFIG_THE_GPU_ISA_HH__
6665517Snate@binkert.org
6675517Snate@binkert.org''')
6685517Snate@binkert.org
6695517Snate@binkert.org    # create defines for the preprocessing and compile-time determination
6705517Snate@binkert.org    for i,isa in enumerate(isas):
6715517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
6725517Snate@binkert.org    code()
6735517Snate@binkert.org
6745517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
6755517Snate@binkert.org    # reuse the same name as the namespaces
6765517Snate@binkert.org    code('enum class GPUArch {')
6775517Snate@binkert.org    for i,isa in enumerate(isas):
6785517Snate@binkert.org        if i + 1 == len(isas):
6795517Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
6805517Snate@binkert.org        else:
6815517Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
6825517Snate@binkert.org    code('};')
6835517Snate@binkert.org
6845517Snate@binkert.org    code('''
6855517Snate@binkert.org
6865517Snate@binkert.org#define THE_GPU_ISA ${{define(target_gpu_isa)}}
6875517Snate@binkert.org#define TheGpuISA ${{namespace(target_gpu_isa)}}
6885517Snate@binkert.org#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
6895517Snate@binkert.org
6905517Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
6915517Snate@binkert.org
6925517Snate@binkert.org    code.write(str(target[0]))
6935517Snate@binkert.org
6945517Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
6955517Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
6965517Snate@binkert.org
6975517Snate@binkert.org########################################################################
6985517Snate@binkert.org#
6995517Snate@binkert.org# Prevent any SimObjects from being added after this point, they
7005517Snate@binkert.org# should all have been added in the SConscripts above
7015517Snate@binkert.org#
7025517Snate@binkert.orgSimObject.fixed = True
7035517Snate@binkert.org
7045517Snate@binkert.orgclass DictImporter(object):
7055517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
7065517Snate@binkert.org    map to arbitrary filenames.'''
7075517Snate@binkert.org    def __init__(self, modules):
7085517Snate@binkert.org        self.modules = modules
7095517Snate@binkert.org        self.installed = set()
7105517Snate@binkert.org
7115517Snate@binkert.org    def __del__(self):
7125517Snate@binkert.org        self.unload()
7135517Snate@binkert.org
7145517Snate@binkert.org    def unload(self):
7155517Snate@binkert.org        import sys
7165517Snate@binkert.org        for module in self.installed:
7175517Snate@binkert.org            del sys.modules[module]
7185517Snate@binkert.org        self.installed = set()
7195517Snate@binkert.org
7205517Snate@binkert.org    def find_module(self, fullname, path):
7215517Snate@binkert.org        if fullname == 'm5.defines':
7225517Snate@binkert.org            return self
7235517Snate@binkert.org
7245517Snate@binkert.org        if fullname == 'm5.objects':
7255517Snate@binkert.org            return self
7265517Snate@binkert.org
7275517Snate@binkert.org        if fullname.startswith('_m5'):
7285517Snate@binkert.org            return None
7295517Snate@binkert.org
7305517Snate@binkert.org        source = self.modules.get(fullname, None)
7315517Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
7325517Snate@binkert.org            return self
7335517Snate@binkert.org
7345517Snate@binkert.org        return None
7355517Snate@binkert.org
7365517Snate@binkert.org    def load_module(self, fullname):
7375517Snate@binkert.org        mod = imp.new_module(fullname)
7385517Snate@binkert.org        sys.modules[fullname] = mod
7395517Snate@binkert.org        self.installed.add(fullname)
7405517Snate@binkert.org
7415517Snate@binkert.org        mod.__loader__ = self
7425517Snate@binkert.org        if fullname == 'm5.objects':
7435517Snate@binkert.org            mod.__path__ = fullname.split('.')
7445517Snate@binkert.org            return mod
7455517Snate@binkert.org
7465517Snate@binkert.org        if fullname == 'm5.defines':
7475517Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
7485517Snate@binkert.org            return mod
7495517Snate@binkert.org
7505517Snate@binkert.org        source = self.modules[fullname]
7515517Snate@binkert.org        if source.modname == '__init__':
7525517Snate@binkert.org            mod.__path__ = source.modpath
7535517Snate@binkert.org        mod.__file__ = source.abspath
7545517Snate@binkert.org
7555517Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
7565517Snate@binkert.org
7575517Snate@binkert.org        return mod
7585517Snate@binkert.org
7595517Snate@binkert.orgimport m5.SimObject
7605517Snate@binkert.orgimport m5.params
7615517Snate@binkert.orgfrom m5.util import code_formatter
7625517Snate@binkert.org
7635517Snate@binkert.orgm5.SimObject.clear()
7645517Snate@binkert.orgm5.params.clear()
7655517Snate@binkert.org
7665517Snate@binkert.org# install the python importer so we can grab stuff from the source
7675517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
7685517Snate@binkert.org# else we won't know about them for the rest of the stuff.
7695517Snate@binkert.orgimporter = DictImporter(PySource.modules)
7705517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
7715517Snate@binkert.org
7725517Snate@binkert.org# import all sim objects so we can populate the all_objects list
7735517Snate@binkert.org# make sure that we're working with a list, then let's sort it
7745517Snate@binkert.orgfor modname in SimObject.modnames:
7755517Snate@binkert.org    exec('from m5.objects import %s' % modname)
7765517Snate@binkert.org
7775517Snate@binkert.org# we need to unload all of the currently imported modules so that they
7785517Snate@binkert.org# will be re-imported the next time the sconscript is run
7795517Snate@binkert.orgimporter.unload()
7805517Snate@binkert.orgsys.meta_path.remove(importer)
7815517Snate@binkert.org
7825517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
7835517Snate@binkert.orgall_enums = m5.params.allEnums
7845517Snate@binkert.org
7855517Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
7865517Snate@binkert.org    for param in obj._params.local.values():
7875517Snate@binkert.org        # load the ptype attribute now because it depends on the
7885517Snate@binkert.org        # current version of SimObject.allClasses, but when scons
7895517Snate@binkert.org        # actually uses the value, all versions of
7905517Snate@binkert.org        # SimObject.allClasses will have been loaded
7915517Snate@binkert.org        param.ptype
7925517Snate@binkert.org
7935517Snate@binkert.org########################################################################
7945517Snate@binkert.org#
7955517Snate@binkert.org# calculate extra dependencies
7965517Snate@binkert.org#
7975517Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
7985517Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
7995517Snate@binkert.orgdepends.sort(key = lambda x: x.name)
8005517Snate@binkert.org
8015517Snate@binkert.org########################################################################
8025517Snate@binkert.org#
8035517Snate@binkert.org# Commands for the basic automatically generated python files
8045517Snate@binkert.org#
8055517Snate@binkert.org
8065517Snate@binkert.org# Generate Python file containing a dict specifying the current
8075517Snate@binkert.org# buildEnv flags.
8085517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
8095517Snate@binkert.org    build_env = source[0].get_contents()
8105517Snate@binkert.org
8115517Snate@binkert.org    code = code_formatter()
8125517Snate@binkert.org    code("""
8135517Snate@binkert.orgimport _m5.core
8145517Snate@binkert.orgimport m5.util
8155517Snate@binkert.org
8165192Ssaidi@eecs.umich.edubuildEnv = m5.util.SmartDict($build_env)
8175517Snate@binkert.org
8185192Ssaidi@eecs.umich.educompileDate = _m5.core.compileDate
8195192Ssaidi@eecs.umich.edu_globals = globals()
8205517Snate@binkert.orgfor key,val in _m5.core.__dict__.iteritems():
8215517Snate@binkert.org    if key.startswith('flag_'):
8225192Ssaidi@eecs.umich.edu        flag = key[5:]
8235192Ssaidi@eecs.umich.edu        _globals[flag] = val
8245456Ssaidi@eecs.umich.edudel _globals
8255517Snate@binkert.org""")
8265517Snate@binkert.org    code.write(target[0].abspath)
8275517Snate@binkert.org
8285517Snate@binkert.orgdefines_info = Value(build_env)
8295517Snate@binkert.org# Generate a file with all of the compile options in it
8305517Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
8315517Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
8325517Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
8335517Snate@binkert.org
8345517Snate@binkert.org# Generate python file containing info about the M5 source code
8355517Snate@binkert.orgdef makeInfoPyFile(target, source, env):
8365517Snate@binkert.org    code = code_formatter()
8375517Snate@binkert.org    for src in source:
8385517Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
8395517Snate@binkert.org        code('$src = ${{repr(data)}}')
8405517Snate@binkert.org    code.write(str(target[0]))
8415517Snate@binkert.org
8425517Snate@binkert.org# Generate a file that wraps the basic top level files
8435517Snate@binkert.orgenv.Command('python/m5/info.py',
8445517Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
8455517Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
8465517Snate@binkert.orgPySource('m5', 'python/m5/info.py')
8475517Snate@binkert.org
8485517Snate@binkert.org########################################################################
8495517Snate@binkert.org#
8505517Snate@binkert.org# Create all of the SimObject param headers and enum headers
8515517Snate@binkert.org#
8525517Snate@binkert.org
8535517Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
8545517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
8555517Snate@binkert.org
8565517Snate@binkert.org    name = source[0].get_text_contents()
8575456Ssaidi@eecs.umich.edu    obj = sim_objects[name]
8585461Snate@binkert.org
8595517Snate@binkert.org    code = code_formatter()
8605456Ssaidi@eecs.umich.edu    obj.cxx_param_decl(code)
8615522Snate@binkert.org    code.write(target[0].abspath)
8625522Snate@binkert.org
8635522Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
8645522Snate@binkert.org    def body(target, source, env):
8655522Snate@binkert.org        assert len(target) == 1 and len(source) == 1
8665522Snate@binkert.org
8675522Snate@binkert.org        name = str(source[0].get_contents())
8685522Snate@binkert.org        obj = sim_objects[name]
8695522Snate@binkert.org
8705517Snate@binkert.org        code = code_formatter()
8715522Snate@binkert.org        obj.cxx_config_param_file(code, is_header)
8725522Snate@binkert.org        code.write(target[0].abspath)
8735522Snate@binkert.org    return body
8745522Snate@binkert.org
8755517Snate@binkert.orgdef createEnumStrings(target, source, env):
8765522Snate@binkert.org    assert len(target) == 1 and len(source) == 2
8775522Snate@binkert.org
8785517Snate@binkert.org    name = source[0].get_text_contents()
8795522Snate@binkert.org    use_python = source[1].read()
8805604Snate@binkert.org    obj = all_enums[name]
8815522Snate@binkert.org
8825522Snate@binkert.org    code = code_formatter()
8835522Snate@binkert.org    obj.cxx_def(code)
8845517Snate@binkert.org    if use_python:
8855522Snate@binkert.org        obj.pybind_def(code)
8865522Snate@binkert.org    code.write(target[0].abspath)
8875522Snate@binkert.org
8885522Snate@binkert.orgdef createEnumDecls(target, source, env):
8895522Snate@binkert.org    assert len(target) == 1 and len(source) == 1
8905522Snate@binkert.org
8915522Snate@binkert.org    name = source[0].get_text_contents()
8925522Snate@binkert.org    obj = all_enums[name]
8935522Snate@binkert.org
8945522Snate@binkert.org    code = code_formatter()
8955522Snate@binkert.org    obj.cxx_decl(code)
8965522Snate@binkert.org    code.write(target[0].abspath)
8975522Snate@binkert.org
8985522Snate@binkert.orgdef createSimObjectPyBindWrapper(target, source, env):
8995522Snate@binkert.org    name = source[0].get_text_contents()
9005522Snate@binkert.org    obj = sim_objects[name]
9015522Snate@binkert.org
9025522Snate@binkert.org    code = code_formatter()
9035522Snate@binkert.org    obj.pybind_decl(code)
9044382Sbinkertn@umich.edu    code.write(target[0].abspath)
9055522Snate@binkert.org
9065522Snate@binkert.org# Generate all of the SimObject param C++ struct header files
9074382Sbinkertn@umich.eduparams_hh_files = []
9085522Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
9095522Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
9105522Snate@binkert.org    extra_deps = [ py_source.tnode ]
9115522Snate@binkert.org
9125522Snate@binkert.org    hh_file = File('params/%s.hh' % name)
9135522Snate@binkert.org    params_hh_files.append(hh_file)
9145522Snate@binkert.org    env.Command(hh_file, Value(name),
9155522Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
9165522Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
9175522Snate@binkert.org
9184382Sbinkertn@umich.edu# C++ parameter description files
9195522Snate@binkert.orgif GetOption('with_cxx_config'):
9205522Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
9215522Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
9225522Snate@binkert.org        extra_deps = [ py_source.tnode ]
9235522Snate@binkert.org
9245522Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
9255522Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
9265522Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
9275522Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
9285522Snate@binkert.org                    Transform("CXXCPRHH")))
9295522Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
9305522Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
9315522Snate@binkert.org                    Transform("CXXCPRCC")))
9325522Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
9335522Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
9345522Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
9355522Snate@binkert.org                    [cxx_config_hh_file])
9365522Snate@binkert.org        Source(cxx_config_cc_file)
9375522Snate@binkert.org
9385522Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
9395522Snate@binkert.org
9405522Snate@binkert.org    def createCxxConfigInitCC(target, source, env):
9415522Snate@binkert.org        assert len(target) == 1 and len(source) == 1
9425522Snate@binkert.org
9435522Snate@binkert.org        code = code_formatter()
9445522Snate@binkert.org
9455522Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
9465522Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
9475522Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
9485522Snate@binkert.org        code()
9495522Snate@binkert.org        code('void cxxConfigInit()')
9504382Sbinkertn@umich.edu        code('{')
9514382Sbinkertn@umich.edu        code.indent()
9524382Sbinkertn@umich.edu        for name,simobj in sorted(sim_objects.iteritems()):
9534382Sbinkertn@umich.edu            not_abstract = not hasattr(simobj, 'abstract') or \
9544382Sbinkertn@umich.edu                not simobj.abstract
9554382Sbinkertn@umich.edu            if not_abstract and 'type' in simobj.__dict__:
9564382Sbinkertn@umich.edu                code('cxx_config_directory["${name}"] = '
9574382Sbinkertn@umich.edu                     '${name}CxxConfigParams::makeDirectoryEntry();')
9584382Sbinkertn@umich.edu        code.dedent()
9594382Sbinkertn@umich.edu        code('}')
960955SN/A        code.write(target[0].abspath)
961955SN/A
962955SN/A    py_source = PySource.modules[simobj.__module__]
963955SN/A    extra_deps = [ py_source.tnode ]
9641108SN/A    env.Command(cxx_config_init_cc_file, Value(name),
9655601Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
9665601Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
9675601Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
9685601Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
9695601Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
9705601Snate@binkert.org            [File('sim/cxx_config.hh')])
9715601Snate@binkert.org    Source(cxx_config_init_cc_file)
9725456Ssaidi@eecs.umich.edu
973955SN/A# Generate all enum header files
974955SN/Afor name,enum in sorted(all_enums.iteritems()):
9755601Snate@binkert.org    py_source = PySource.modules[enum.__module__]
9765456Ssaidi@eecs.umich.edu    extra_deps = [ py_source.tnode ]
9775456Ssaidi@eecs.umich.edu
9785456Ssaidi@eecs.umich.edu    cc_file = File('enums/%s.cc' % name)
9795456Ssaidi@eecs.umich.edu    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
9805601Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
9815456Ssaidi@eecs.umich.edu    env.Depends(cc_file, depends + extra_deps)
982955SN/A    Source(cc_file)
9835456Ssaidi@eecs.umich.edu
9845601Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
985955SN/A    env.Command(hh_file, Value(name),
986955SN/A                MakeAction(createEnumDecls, Transform("ENUMDECL")))
9872655Sstever@eecs.umich.edu    env.Depends(hh_file, depends + extra_deps)
9882655Sstever@eecs.umich.edu
9892655Sstever@eecs.umich.edu# Generate SimObject Python bindings wrapper files
9902655Sstever@eecs.umich.eduif env['USE_PYTHON']:
9912655Sstever@eecs.umich.edu    for name,simobj in sorted(sim_objects.iteritems()):
9925601Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
9935601Snate@binkert.org        extra_deps = [ py_source.tnode ]
9945601Snate@binkert.org        cc_file = File('python/_m5/param_%s.cc' % name)
9955601Snate@binkert.org        env.Command(cc_file, Value(name),
9965522Snate@binkert.org                    MakeAction(createSimObjectPyBindWrapper,
9975601Snate@binkert.org                               Transform("SO PyBind")))
9985601Snate@binkert.org        env.Depends(cc_file, depends + extra_deps)
9995601Snate@binkert.org        Source(cc_file)
10005601Snate@binkert.org
10015601Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
10025559Snate@binkert.orgif env['HAVE_PROTOBUF']:
10035559Snate@binkert.org    for proto in ProtoBuf.all:
10045559Snate@binkert.org        # Use both the source and header as the target, and the .proto
10055559Snate@binkert.org        # file as the source. When executing the protoc compiler, also
10065601Snate@binkert.org        # specify the proto_path to avoid having the generated files
10075601Snate@binkert.org        # include the path.
10085601Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
10095601Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
10105601Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
10115554Snate@binkert.org                               Transform("PROTOC")))
10125522Snate@binkert.org
10135522Snate@binkert.org        # Add the C++ source file
10145601Snate@binkert.org        Source(proto.cc_file, tags=proto.tags)
10155601Snate@binkert.orgelif ProtoBuf.all:
10165522Snate@binkert.org    print('Got protobuf to build, but lacks support!')
10175584Snate@binkert.org    Exit(1)
10185601Snate@binkert.org
10195601Snate@binkert.org#
10205584Snate@binkert.org# Handle debug flags
10215601Snate@binkert.org#
10225601Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
10232655Sstever@eecs.umich.edu    assert(len(target) == 1 and len(source) == 1)
10245601Snate@binkert.org
10255601Snate@binkert.org    code = code_formatter()
10264007Ssaidi@eecs.umich.edu
10274596Sbinkertn@umich.edu    # delay definition of CompoundFlags until after all the definition
10284007Ssaidi@eecs.umich.edu    # of all constituent SimpleFlags
10294596Sbinkertn@umich.edu    comp_code = code_formatter()
10305601Snate@binkert.org
10315522Snate@binkert.org    # file header
10325601Snate@binkert.org    code('''
10335522Snate@binkert.org/*
10345601Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
10355601Snate@binkert.org */
10362655Sstever@eecs.umich.edu
1037955SN/A#include "base/debug.hh"
10383918Ssaidi@eecs.umich.edu
10393918Ssaidi@eecs.umich.edunamespace Debug {
10403918Ssaidi@eecs.umich.edu
10413918Ssaidi@eecs.umich.edu''')
10423918Ssaidi@eecs.umich.edu
10433918Ssaidi@eecs.umich.edu    for name, flag in sorted(source[0].read().iteritems()):
10443918Ssaidi@eecs.umich.edu        n, compound, desc = flag
10453918Ssaidi@eecs.umich.edu        assert n == name
10463918Ssaidi@eecs.umich.edu
10473918Ssaidi@eecs.umich.edu        if not compound:
10483918Ssaidi@eecs.umich.edu            code('SimpleFlag $name("$name", "$desc");')
10493918Ssaidi@eecs.umich.edu        else:
10503918Ssaidi@eecs.umich.edu            comp_code('CompoundFlag $name("$name", "$desc",')
10513918Ssaidi@eecs.umich.edu            comp_code.indent()
10523940Ssaidi@eecs.umich.edu            last = len(compound) - 1
10533940Ssaidi@eecs.umich.edu            for i,flag in enumerate(compound):
10543940Ssaidi@eecs.umich.edu                if i != last:
10553942Ssaidi@eecs.umich.edu                    comp_code('&$flag,')
10563940Ssaidi@eecs.umich.edu                else:
10573515Ssaidi@eecs.umich.edu                    comp_code('&$flag);')
10583918Ssaidi@eecs.umich.edu            comp_code.dedent()
10594762Snate@binkert.org
10603515Ssaidi@eecs.umich.edu    code.append(comp_code)
10612655Sstever@eecs.umich.edu    code()
10623918Ssaidi@eecs.umich.edu    code('} // namespace Debug')
10633619Sbinkertn@umich.edu
1064955SN/A    code.write(str(target[0]))
1065955SN/A
10662655Sstever@eecs.umich.edudef makeDebugFlagHH(target, source, env):
10673918Ssaidi@eecs.umich.edu    assert(len(target) == 1 and len(source) == 1)
10683619Sbinkertn@umich.edu
1069955SN/A    val = eval(source[0].get_contents())
1070955SN/A    name, compound, desc = val
10712655Sstever@eecs.umich.edu
10723918Ssaidi@eecs.umich.edu    code = code_formatter()
10733619Sbinkertn@umich.edu
1074955SN/A    # file header boilerplate
1075955SN/A    code('''\
10762655Sstever@eecs.umich.edu/*
10773918Ssaidi@eecs.umich.edu * DO NOT EDIT THIS FILE! Automatically generated by SCons.
10783683Sstever@eecs.umich.edu */
10792655Sstever@eecs.umich.edu
10801869SN/A#ifndef __DEBUG_${name}_HH__
10811869SN/A#define __DEBUG_${name}_HH__
1082
1083namespace Debug {
1084''')
1085
1086    if compound:
1087        code('class CompoundFlag;')
1088    code('class SimpleFlag;')
1089
1090    if compound:
1091        code('extern CompoundFlag $name;')
1092        for flag in compound:
1093            code('extern SimpleFlag $flag;')
1094    else:
1095        code('extern SimpleFlag $name;')
1096
1097    code('''
1098}
1099
1100#endif // __DEBUG_${name}_HH__
1101''')
1102
1103    code.write(str(target[0]))
1104
1105for name,flag in sorted(debug_flags.iteritems()):
1106    n, compound, desc = flag
1107    assert n == name
1108
1109    hh_file = 'debug/%s.hh' % name
1110    env.Command(hh_file, Value(flag),
1111                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
1112
1113env.Command('debug/flags.cc', Value(debug_flags),
1114            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
1115Source('debug/flags.cc')
1116
1117# version tags
1118tags = \
1119env.Command('sim/tags.cc', None,
1120            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
1121                       Transform("VER TAGS")))
1122env.AlwaysBuild(tags)
1123
1124# Embed python files.  All .py files that have been indicated by a
1125# PySource() call in a SConscript need to be embedded into the M5
1126# library.  To do that, we compile the file to byte code, marshal the
1127# byte code, compress it, and then generate a c++ file that
1128# inserts the result into an array.
1129def embedPyFile(target, source, env):
1130    def c_str(string):
1131        if string is None:
1132            return "0"
1133        return '"%s"' % string
1134
1135    '''Action function to compile a .py into a code object, marshal
1136    it, compress it, and stick it into an asm file so the code appears
1137    as just bytes with a label in the data section'''
1138
1139    src = file(str(source[0]), 'r').read()
1140
1141    pysource = PySource.tnodes[source[0]]
1142    compiled = compile(src, pysource.abspath, 'exec')
1143    marshalled = marshal.dumps(compiled)
1144    compressed = zlib.compress(marshalled)
1145    data = compressed
1146    sym = pysource.symname
1147
1148    code = code_formatter()
1149    code('''\
1150#include "sim/init.hh"
1151
1152namespace {
1153
1154''')
1155    blobToCpp(data, 'data_' + sym, code)
1156    code('''\
1157
1158
1159EmbeddedPython embedded_${sym}(
1160    ${{c_str(pysource.arcname)}},
1161    ${{c_str(pysource.abspath)}},
1162    ${{c_str(pysource.modpath)}},
1163    data_${sym},
1164    ${{len(data)}},
1165    ${{len(marshalled)}});
1166
1167} // anonymous namespace
1168''')
1169    code.write(str(target[0]))
1170
1171for source in PySource.all:
1172    env.Command(source.cpp, source.tnode,
1173                MakeAction(embedPyFile, Transform("EMBED PY")))
1174    Source(source.cpp, tags=source.tags, add_tags='python')
1175
1176########################################################################
1177#
1178# Define binaries.  Each different build type (debug, opt, etc.) gets
1179# a slightly different build environment.
1180#
1181
1182# List of constructed environments to pass back to SConstruct
1183date_source = Source('base/date.cc', tags=[])
1184
1185gem5_binary = Gem5('gem5')
1186
1187# Function to create a new build environment as clone of current
1188# environment 'env' with modified object suffix and optional stripped
1189# binary.  Additional keyword arguments are appended to corresponding
1190# build environment vars.
1191def makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
1192    # SCons doesn't know to append a library suffix when there is a '.' in the
1193    # name.  Use '_' instead.
1194    libname = 'gem5_' + label
1195    secondary_exename = 'm5.' + label
1196
1197    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
1198    new_env.Label = label
1199    new_env.Append(**kwargs)
1200
1201    lib_sources = Source.all.with_tag('gem5 lib')
1202
1203    # Without Python, leave out all Python content from the library
1204    # builds.  The option doesn't affect gem5 built as a program
1205    if GetOption('without_python'):
1206        lib_sources = lib_sources.without_tag('python')
1207
1208    static_objs = []
1209    shared_objs = []
1210
1211    for s in lib_sources.with_tag(Source.ungrouped_tag):
1212        static_objs.append(s.static(new_env))
1213        shared_objs.append(s.shared(new_env))
1214
1215    for group in Source.source_groups:
1216        srcs = lib_sources.with_tag(Source.link_group_tag(group))
1217        if not srcs:
1218            continue
1219
1220        group_static = [ s.static(new_env) for s in srcs ]
1221        group_shared = [ s.shared(new_env) for s in srcs ]
1222
1223        # If partial linking is disabled, add these sources to the build
1224        # directly, and short circuit this loop.
1225        if disable_partial:
1226            static_objs.extend(group_static)
1227            shared_objs.extend(group_shared)
1228            continue
1229
1230        # Set up the static partially linked objects.
1231        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
1232        target = File(joinpath(group, file_name))
1233        partial = env.PartialStatic(target=target, source=group_static)
1234        static_objs.extend(partial)
1235
1236        # Set up the shared partially linked objects.
1237        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
1238        target = File(joinpath(group, file_name))
1239        partial = env.PartialShared(target=target, source=group_shared)
1240        shared_objs.extend(partial)
1241
1242    static_date = date_source.static(new_env)
1243    new_env.Depends(static_date, static_objs)
1244    static_objs.extend(static_date)
1245
1246    shared_date = date_source.shared(new_env)
1247    new_env.Depends(shared_date, shared_objs)
1248    shared_objs.extend(shared_date)
1249
1250    main_objs = [ s.static(new_env) for s in Source.all.with_tag('main') ]
1251
1252    # First make a library of everything but main() so other programs can
1253    # link against m5.
1254    static_lib = new_env.StaticLibrary(libname, static_objs)
1255    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1256
1257    # Keep track of the object files generated so far so Executables can
1258    # include them.
1259    new_env['STATIC_OBJS'] = static_objs
1260    new_env['SHARED_OBJS'] = shared_objs
1261    new_env['MAIN_OBJS'] = main_objs
1262
1263    new_env['STATIC_LIB'] = static_lib
1264    new_env['SHARED_LIB'] = shared_lib
1265
1266    # Record some settings for building Executables.
1267    new_env['EXE_SUFFIX'] = label
1268    new_env['STRIP_EXES'] = strip
1269
1270    for cls in ExecutableMeta.all:
1271        cls.declare_all(new_env)
1272
1273    new_env.M5Binary = File(gem5_binary.path(new_env))
1274
1275    new_env.Command(secondary_exename, new_env.M5Binary,
1276            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1277
1278    # Set up regression tests.
1279    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1280               variant_dir=Dir('tests').Dir(new_env.Label),
1281               exports={ 'env' : new_env }, duplicate=False)
1282
1283# Start out with the compiler flags common to all compilers,
1284# i.e. they all use -g for opt and -g -pg for prof
1285ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1286           'perf' : ['-g']}
1287
1288# Start out with the linker flags common to all linkers, i.e. -pg for
1289# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1290# no-as-needed and as-needed as the binutils linker is too clever and
1291# simply doesn't link to the library otherwise.
1292ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1293           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1294
1295# For Link Time Optimization, the optimisation flags used to compile
1296# individual files are decoupled from those used at link time
1297# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1298# to also update the linker flags based on the target.
1299if env['GCC']:
1300    if sys.platform == 'sunos5':
1301        ccflags['debug'] += ['-gstabs+']
1302    else:
1303        ccflags['debug'] += ['-ggdb3']
1304    ldflags['debug'] += ['-O0']
1305    # opt, fast, prof and perf all share the same cc flags, also add
1306    # the optimization to the ldflags as LTO defers the optimization
1307    # to link time
1308    for target in ['opt', 'fast', 'prof', 'perf']:
1309        ccflags[target] += ['-O3']
1310        ldflags[target] += ['-O3']
1311
1312    ccflags['fast'] += env['LTO_CCFLAGS']
1313    ldflags['fast'] += env['LTO_LDFLAGS']
1314elif env['CLANG']:
1315    ccflags['debug'] += ['-g', '-O0']
1316    # opt, fast, prof and perf all share the same cc flags
1317    for target in ['opt', 'fast', 'prof', 'perf']:
1318        ccflags[target] += ['-O3']
1319else:
1320    print('Unknown compiler, please fix compiler options')
1321    Exit(1)
1322
1323
1324# To speed things up, we only instantiate the build environments we
1325# need.  We try to identify the needed environment for each target; if
1326# we can't, we fall back on instantiating all the environments just to
1327# be safe.
1328target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1329obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1330              'gpo' : 'perf'}
1331
1332def identifyTarget(t):
1333    ext = t.split('.')[-1]
1334    if ext in target_types:
1335        return ext
1336    if obj2target.has_key(ext):
1337        return obj2target[ext]
1338    match = re.search(r'/tests/([^/]+)/', t)
1339    if match and match.group(1) in target_types:
1340        return match.group(1)
1341    return 'all'
1342
1343needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1344if 'all' in needed_envs:
1345    needed_envs += target_types
1346
1347disable_partial = False
1348if env['PLATFORM'] == 'darwin':
1349    # Up until Apple LLVM version 10.0.0 (clang-1000.11.45.5), partial
1350    # linked objects do not expose symbols that are marked with the
1351    # hidden visibility and consequently building gem5 on Mac OS
1352    # fails. As a workaround, we disable partial linking, however, we
1353    # may want to revisit in the future.
1354    disable_partial = True
1355
1356# Debug binary
1357if 'debug' in needed_envs:
1358    makeEnv(env, 'debug', '.do',
1359            CCFLAGS = Split(ccflags['debug']),
1360            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1361            LINKFLAGS = Split(ldflags['debug']),
1362            disable_partial=disable_partial)
1363
1364# Optimized binary
1365if 'opt' in needed_envs:
1366    makeEnv(env, 'opt', '.o',
1367            CCFLAGS = Split(ccflags['opt']),
1368            CPPDEFINES = ['TRACING_ON=1'],
1369            LINKFLAGS = Split(ldflags['opt']),
1370            disable_partial=disable_partial)
1371
1372# "Fast" binary
1373if 'fast' in needed_envs:
1374    disable_partial = disable_partial and \
1375            env.get('BROKEN_INCREMENTAL_LTO', False) and \
1376            GetOption('force_lto')
1377    makeEnv(env, 'fast', '.fo', strip = True,
1378            CCFLAGS = Split(ccflags['fast']),
1379            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1380            LINKFLAGS = Split(ldflags['fast']),
1381            disable_partial=disable_partial)
1382
1383# Profiled binary using gprof
1384if 'prof' in needed_envs:
1385    makeEnv(env, 'prof', '.po',
1386            CCFLAGS = Split(ccflags['prof']),
1387            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1388            LINKFLAGS = Split(ldflags['prof']),
1389            disable_partial=disable_partial)
1390
1391# Profiled binary using google-pprof
1392if 'perf' in needed_envs:
1393    makeEnv(env, 'perf', '.gpo',
1394            CCFLAGS = Split(ccflags['perf']),
1395            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1396            LINKFLAGS = Split(ldflags['perf']),
1397            disable_partial=disable_partial)
1398