SConscript revision 13993
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
326143Snate@binkert.org# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
334762Snate@binkert.org# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
345522Snate@binkert.org# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
365522Snate@binkert.org# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
385522Snate@binkert.org# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
394202Sbinkertn@umich.edu#
405742Snate@binkert.org# Authors: Nathan Binkert
41955SN/A
424381Sbinkertn@umich.edufrom __future__ import print_function
434381Sbinkertn@umich.edu
448334Snate@binkert.orgimport array
45955SN/Aimport bisect
46955SN/Aimport functools
474202Sbinkertn@umich.eduimport imp
48955SN/Aimport os
494382Sbinkertn@umich.eduimport re
504382Sbinkertn@umich.eduimport sys
514382Sbinkertn@umich.eduimport zlib
526654Snate@binkert.org
535517Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
548614Sgblack@eecs.umich.edu
557674Snate@binkert.orgimport SCons
566143Snate@binkert.org
576143Snate@binkert.orgfrom gem5_scons import Transform
586143Snate@binkert.org
598233Snate@binkert.org# This file defines how to build a particular configuration of gem5
608233Snate@binkert.org# based on variable settings in the 'env' build environment.
618233Snate@binkert.org
628233Snate@binkert.orgImport('*')
638233Snate@binkert.org
648334Snate@binkert.org# Children need to see the environment
658334Snate@binkert.orgExport('env')
668233Snate@binkert.org
678233Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
688233Snate@binkert.org
698233Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
708233Snate@binkert.org
718233Snate@binkert.org########################################################################
726143Snate@binkert.org# Code for adding source files of various types
738233Snate@binkert.org#
748233Snate@binkert.org# When specifying a source file of some type, a set of tags can be
758233Snate@binkert.org# specified for that file.
766143Snate@binkert.org
776143Snate@binkert.orgclass SourceFilter(object):
786143Snate@binkert.org    def __init__(self, predicate):
796143Snate@binkert.org        self.predicate = predicate
808233Snate@binkert.org
818233Snate@binkert.org    def __or__(self, other):
828233Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) or
836143Snate@binkert.org                                         other.predicate(tags))
848233Snate@binkert.org
858233Snate@binkert.org    def __and__(self, other):
868233Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) and
878233Snate@binkert.org                                         other.predicate(tags))
886143Snate@binkert.org
896143Snate@binkert.orgdef with_tags_that(predicate):
906143Snate@binkert.org    '''Return a list of sources with tags that satisfy a predicate.'''
914762Snate@binkert.org    return SourceFilter(predicate)
926143Snate@binkert.org
938233Snate@binkert.orgdef with_any_tags(*tags):
948233Snate@binkert.org    '''Return a list of sources with any of the supplied tags.'''
958233Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) > 0)
968233Snate@binkert.org
978233Snate@binkert.orgdef with_all_tags(*tags):
986143Snate@binkert.org    '''Return a list of sources with all of the supplied tags.'''
998233Snate@binkert.org    return SourceFilter(lambda stags: set(tags) <= stags)
1008233Snate@binkert.org
1018233Snate@binkert.orgdef with_tag(tag):
1028233Snate@binkert.org    '''Return a list of sources with the supplied tag.'''
1036143Snate@binkert.org    return SourceFilter(lambda stags: tag in stags)
1046143Snate@binkert.org
1056143Snate@binkert.orgdef without_tags(*tags):
1066143Snate@binkert.org    '''Return a list of sources without any of the supplied tags.'''
1076143Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) == 0)
1086143Snate@binkert.org
1096143Snate@binkert.orgdef without_tag(tag):
1106143Snate@binkert.org    '''Return a list of sources with the supplied tag.'''
1116143Snate@binkert.org    return SourceFilter(lambda stags: tag not in stags)
1127065Snate@binkert.org
1136143Snate@binkert.orgsource_filter_factories = {
1148233Snate@binkert.org    'with_tags_that': with_tags_that,
1158233Snate@binkert.org    'with_any_tags': with_any_tags,
1168233Snate@binkert.org    'with_all_tags': with_all_tags,
1178233Snate@binkert.org    'with_tag': with_tag,
1188233Snate@binkert.org    'without_tags': without_tags,
1198233Snate@binkert.org    'without_tag': without_tag,
1208233Snate@binkert.org}
1218233Snate@binkert.org
1228233Snate@binkert.orgExport(source_filter_factories)
1238233Snate@binkert.org
1248233Snate@binkert.orgclass SourceList(list):
1258233Snate@binkert.org    def apply_filter(self, f):
1268233Snate@binkert.org        def match(source):
1278233Snate@binkert.org            return f.predicate(source.tags)
1288233Snate@binkert.org        return SourceList(filter(match, self))
1298233Snate@binkert.org
1308233Snate@binkert.org    def __getattr__(self, name):
1318233Snate@binkert.org        func = source_filter_factories.get(name, None)
1328233Snate@binkert.org        if not func:
1338233Snate@binkert.org            raise AttributeError
1348233Snate@binkert.org
1358233Snate@binkert.org        @functools.wraps(func)
1368233Snate@binkert.org        def wrapper(*args, **kwargs):
1378233Snate@binkert.org            return self.apply_filter(func(*args, **kwargs))
1388233Snate@binkert.org        return wrapper
1398233Snate@binkert.org
1408233Snate@binkert.orgclass SourceMeta(type):
1418233Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
1428233Snate@binkert.org    particular type.'''
1438233Snate@binkert.org    def __init__(cls, name, bases, dict):
1448233Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
1456143Snate@binkert.org        cls.all = SourceList()
1466143Snate@binkert.org
1476143Snate@binkert.orgclass SourceFile(object):
1486143Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1496143Snate@binkert.org    This includes, the source node, target node, various manipulations
1506143Snate@binkert.org    of those.  A source file also specifies a set of tags which
1516143Snate@binkert.org    describing arbitrary properties of the source file.'''
1526143Snate@binkert.org    __metaclass__ = SourceMeta
1536143Snate@binkert.org
1548945Ssteve.reinhardt@amd.com    static_objs = {}
1558233Snate@binkert.org    shared_objs = {}
1568233Snate@binkert.org
1576143Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
1588945Ssteve.reinhardt@amd.com        if tags is None:
1596143Snate@binkert.org            tags='gem5 lib'
1606143Snate@binkert.org        if isinstance(tags, basestring):
1616143Snate@binkert.org            tags = set([tags])
1626143Snate@binkert.org        if not isinstance(tags, set):
1635522Snate@binkert.org            tags = set(tags)
1646143Snate@binkert.org        self.tags = tags
1656143Snate@binkert.org
1666143Snate@binkert.org        if add_tags:
1676143Snate@binkert.org            if isinstance(add_tags, basestring):
1688233Snate@binkert.org                add_tags = set([add_tags])
1698233Snate@binkert.org            if not isinstance(add_tags, set):
1708233Snate@binkert.org                add_tags = set(add_tags)
1716143Snate@binkert.org            self.tags |= add_tags
1726143Snate@binkert.org
1736143Snate@binkert.org        tnode = source
1746143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1755522Snate@binkert.org            tnode = File(source)
1765522Snate@binkert.org
1775522Snate@binkert.org        self.tnode = tnode
1785522Snate@binkert.org        self.snode = tnode.srcnode()
1795604Snate@binkert.org
1805604Snate@binkert.org        for base in type(self).__mro__:
1816143Snate@binkert.org            if issubclass(base, SourceFile):
1826143Snate@binkert.org                base.all.append(self)
1834762Snate@binkert.org
1844762Snate@binkert.org    def static(self, env):
1856143Snate@binkert.org        key = (self.tnode, env['OBJSUFFIX'])
1866727Ssteve.reinhardt@amd.com        if not key in self.static_objs:
1876727Ssteve.reinhardt@amd.com            self.static_objs[key] = env.StaticObject(self.tnode)
1886727Ssteve.reinhardt@amd.com        return self.static_objs[key]
1894762Snate@binkert.org
1906143Snate@binkert.org    def shared(self, env):
1916143Snate@binkert.org        key = (self.tnode, env['OBJSUFFIX'])
1926143Snate@binkert.org        if not key in self.shared_objs:
1936143Snate@binkert.org            self.shared_objs[key] = env.SharedObject(self.tnode)
1946727Ssteve.reinhardt@amd.com        return self.shared_objs[key]
1956143Snate@binkert.org
1967674Snate@binkert.org    @property
1977674Snate@binkert.org    def filename(self):
1985604Snate@binkert.org        return str(self.tnode)
1996143Snate@binkert.org
2006143Snate@binkert.org    @property
2016143Snate@binkert.org    def dirname(self):
2024762Snate@binkert.org        return dirname(self.filename)
2036143Snate@binkert.org
2044762Snate@binkert.org    @property
2054762Snate@binkert.org    def basename(self):
2064762Snate@binkert.org        return basename(self.filename)
2076143Snate@binkert.org
2086143Snate@binkert.org    @property
2094762Snate@binkert.org    def extname(self):
2108233Snate@binkert.org        index = self.basename.rfind('.')
2118233Snate@binkert.org        if index <= 0:
2128233Snate@binkert.org            # dot files aren't extensions
2138233Snate@binkert.org            return self.basename, None
2146143Snate@binkert.org
2156143Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
2164762Snate@binkert.org
2176143Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
2184762Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
2196143Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
2204762Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
2216143Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
2228233Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
2238233Snate@binkert.org
2248233Snate@binkert.orgdef blobToCpp(data, symbol, cpp_code, hpp_code=None, namespace=None):
2256143Snate@binkert.org    '''
2266143Snate@binkert.org    Convert bytes data into C++ .cpp and .hh uint8_t byte array
2276143Snate@binkert.org    code containing that binary data.
2286143Snate@binkert.org
2296143Snate@binkert.org    :param data: binary data to be converted to C++
2306143Snate@binkert.org    :param symbol: name of the symbol
2316143Snate@binkert.org    :param cpp_code: append the generated cpp_code to this object
2326143Snate@binkert.org    :param hpp_code: append the generated hpp_code to this object
2338233Snate@binkert.org                     If None, ignore it. Otherwise, also include it
2348233Snate@binkert.org                     in the .cpp file.
235955SN/A    :param namespace: namespace to put the symbol into. If None,
2368235Snate@binkert.org                      don't put the symbols into any namespace.
2378235Snate@binkert.org    '''
2386143Snate@binkert.org    symbol_len_declaration = 'const std::size_t {}_len'.format(symbol)
2398235Snate@binkert.org    symbol_declaration = 'const std::uint8_t {}[]'.format(symbol)
2409003SAli.Saidi@ARM.com    if hpp_code is not None:
2418235Snate@binkert.org        cpp_code('''\
2428235Snate@binkert.org#include "blobs/{}.hh"
2438235Snate@binkert.org'''.format(symbol))
2448235Snate@binkert.org        hpp_code('''\
2458235Snate@binkert.org#include <cstddef>
2468235Snate@binkert.org#include <cstdint>
2478235Snate@binkert.org''')
2488235Snate@binkert.org        if namespace is not None:
2498235Snate@binkert.org            hpp_code('namespace {} {{'.format(namespace))
2508235Snate@binkert.org        hpp_code('extern ' + symbol_len_declaration + ';')
2518235Snate@binkert.org        hpp_code('extern ' + symbol_declaration + ';')
2528235Snate@binkert.org        if namespace is not None:
2538235Snate@binkert.org            hpp_code('}')
2548235Snate@binkert.org    if namespace is not None:
2559003SAli.Saidi@ARM.com        cpp_code('namespace {} {{'.format(namespace))
2568235Snate@binkert.org    if hpp_code is not None:
2575584Snate@binkert.org        cpp_code(symbol_len_declaration + ' = {};'.format(len(data)))
2584382Sbinkertn@umich.edu    cpp_code(symbol_declaration + ' = {')
2594202Sbinkertn@umich.edu    cpp_code.indent()
2604382Sbinkertn@umich.edu    step = 16
2614382Sbinkertn@umich.edu    for i in xrange(0, len(data), step):
2624382Sbinkertn@umich.edu        x = array.array('B', data[i:i+step])
2635584Snate@binkert.org        cpp_code(''.join('%d,' % d for d in x))
2644382Sbinkertn@umich.edu    cpp_code.dedent()
2654382Sbinkertn@umich.edu    cpp_code('};')
2664382Sbinkertn@umich.edu    if namespace is not None:
2678232Snate@binkert.org        cpp_code('}')
2685192Ssaidi@eecs.umich.edu
2698232Snate@binkert.orgdef Blob(blob_path, symbol):
2708232Snate@binkert.org    '''
2718232Snate@binkert.org    Embed an arbitrary blob into the gem5 executable,
2725192Ssaidi@eecs.umich.edu    and make it accessible to C++ as a byte array.
2738232Snate@binkert.org    '''
2745192Ssaidi@eecs.umich.edu    blob_path = os.path.abspath(blob_path)
2755799Snate@binkert.org    blob_out_dir = os.path.join(env['BUILDDIR'], 'blobs')
2768232Snate@binkert.org    path_noext = joinpath(blob_out_dir, symbol)
2775192Ssaidi@eecs.umich.edu    cpp_path = path_noext + '.cc'
2785192Ssaidi@eecs.umich.edu    hpp_path = path_noext + '.hh'
2795192Ssaidi@eecs.umich.edu    def embedBlob(target, source, env):
2808232Snate@binkert.org        data = file(str(source[0]), 'r').read()
2815192Ssaidi@eecs.umich.edu        cpp_code = code_formatter()
2828232Snate@binkert.org        hpp_code = code_formatter()
2835192Ssaidi@eecs.umich.edu        blobToCpp(data, symbol, cpp_code, hpp_code, namespace='Blobs')
2845192Ssaidi@eecs.umich.edu        cpp_path = str(target[0])
2855192Ssaidi@eecs.umich.edu        hpp_path = str(target[1])
2865192Ssaidi@eecs.umich.edu        cpp_dir = os.path.split(cpp_path)[0]
2874382Sbinkertn@umich.edu        if not os.path.exists(cpp_dir):
2884382Sbinkertn@umich.edu            os.makedirs(cpp_dir)
2894382Sbinkertn@umich.edu        cpp_code.write(cpp_path)
2902667Sstever@eecs.umich.edu        hpp_code.write(hpp_path)
2912667Sstever@eecs.umich.edu    env.Command([cpp_path, hpp_path], blob_path,
2922667Sstever@eecs.umich.edu                MakeAction(embedBlob, Transform("EMBED BLOB")))
2932667Sstever@eecs.umich.edu    Source(cpp_path)
2942667Sstever@eecs.umich.edu
2952667Sstever@eecs.umich.edudef GdbXml(xml_id, symbol):
2965742Snate@binkert.org    Blob(joinpath(gdb_xml_dir, xml_id), symbol)
2975742Snate@binkert.org
2985742Snate@binkert.orgclass Source(SourceFile):
2995793Snate@binkert.org    ungrouped_tag = 'No link group'
3008334Snate@binkert.org    source_groups = set()
3015793Snate@binkert.org
3025793Snate@binkert.org    _current_group_tag = ungrouped_tag
3035793Snate@binkert.org
3044382Sbinkertn@umich.edu    @staticmethod
3054762Snate@binkert.org    def link_group_tag(group):
3065344Sstever@gmail.com        return 'link group: %s' % group
3074382Sbinkertn@umich.edu
3085341Sstever@gmail.com    @classmethod
3095742Snate@binkert.org    def set_group(cls, group):
3105742Snate@binkert.org        new_tag = Source.link_group_tag(group)
3115742Snate@binkert.org        Source._current_group_tag = new_tag
3125742Snate@binkert.org        Source.source_groups.add(group)
3135742Snate@binkert.org
3144762Snate@binkert.org    def _add_link_group_tag(self):
3155742Snate@binkert.org        self.tags.add(Source._current_group_tag)
3165742Snate@binkert.org
3177722Sgblack@eecs.umich.edu    '''Add a c/c++ source file to the build'''
3185742Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3195742Snate@binkert.org        '''specify the source file, and any tags'''
3205742Snate@binkert.org        super(Source, self).__init__(source, tags, add_tags)
3215742Snate@binkert.org        self._add_link_group_tag()
3228242Sbradley.danofsky@amd.com
3238242Sbradley.danofsky@amd.comclass PySource(SourceFile):
3248242Sbradley.danofsky@amd.com    '''Add a python source file to the named package'''
3258242Sbradley.danofsky@amd.com    invalid_sym_char = re.compile('[^A-z0-9_]')
3265341Sstever@gmail.com    modules = {}
3275742Snate@binkert.org    tnodes = {}
3287722Sgblack@eecs.umich.edu    symnames = {}
3294773Snate@binkert.org
3306108Snate@binkert.org    def __init__(self, package, source, tags=None, add_tags=None):
3311858SN/A        '''specify the python package, the source file, and any tags'''
3321085SN/A        super(PySource, self).__init__(source, tags, add_tags)
3336658Snate@binkert.org
3346658Snate@binkert.org        modname,ext = self.extname
3357673Snate@binkert.org        assert ext == 'py'
3366658Snate@binkert.org
3376658Snate@binkert.org        if package:
3386658Snate@binkert.org            path = package.split('.')
3396658Snate@binkert.org        else:
3406658Snate@binkert.org            path = []
3416658Snate@binkert.org
3426658Snate@binkert.org        modpath = path[:]
3437673Snate@binkert.org        if modname != '__init__':
3447673Snate@binkert.org            modpath += [ modname ]
3457673Snate@binkert.org        modpath = '.'.join(modpath)
3467673Snate@binkert.org
3477673Snate@binkert.org        arcpath = path + [ self.basename ]
3487673Snate@binkert.org        abspath = self.snode.abspath
3497673Snate@binkert.org        if not exists(abspath):
3506658Snate@binkert.org            abspath = self.tnode.abspath
3517673Snate@binkert.org
3527673Snate@binkert.org        self.package = package
3537673Snate@binkert.org        self.modname = modname
3547673Snate@binkert.org        self.modpath = modpath
3557673Snate@binkert.org        self.arcname = joinpath(*arcpath)
3567673Snate@binkert.org        self.abspath = abspath
3579048SAli.Saidi@ARM.com        self.compiled = File(self.filename + 'c')
3587673Snate@binkert.org        self.cpp = File(self.filename + '.cc')
3597673Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
3607673Snate@binkert.org
3617673Snate@binkert.org        PySource.modules[modpath] = self
3626658Snate@binkert.org        PySource.tnodes[self.tnode] = self
3637756SAli.Saidi@ARM.com        PySource.symnames[self.symname] = self
3647816Ssteve.reinhardt@amd.com
3656658Snate@binkert.orgclass SimObject(PySource):
3664382Sbinkertn@umich.edu    '''Add a SimObject python file as a python source object and add
3674382Sbinkertn@umich.edu    it to a list of sim object modules'''
3684762Snate@binkert.org
3694762Snate@binkert.org    fixed = False
3704762Snate@binkert.org    modnames = []
3716654Snate@binkert.org
3726654Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3735517Snate@binkert.org        '''Specify the source file and any tags (automatically in
3745517Snate@binkert.org        the m5.objects package)'''
3755517Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)
3765517Snate@binkert.org        if self.fixed:
3775517Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
3785517Snate@binkert.org
3795517Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
3805517Snate@binkert.org
3815517Snate@binkert.orgclass ProtoBuf(SourceFile):
3825517Snate@binkert.org    '''Add a Protocol Buffer to build'''
3835517Snate@binkert.org
3845517Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3855517Snate@binkert.org        '''Specify the source file, and any tags'''
3865517Snate@binkert.org        super(ProtoBuf, self).__init__(source, tags, add_tags)
3875517Snate@binkert.org
3885517Snate@binkert.org        # Get the file name and the extension
3895517Snate@binkert.org        modname,ext = self.extname
3906654Snate@binkert.org        assert ext == 'proto'
3915517Snate@binkert.org
3925517Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
3935517Snate@binkert.org        # only need to track the source and header.
3945517Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
3955517Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
3965517Snate@binkert.org
3975517Snate@binkert.org
3985517Snate@binkert.orgexectuable_classes = []
3996143Snate@binkert.orgclass ExecutableMeta(type):
4006654Snate@binkert.org    '''Meta class for Executables.'''
4015517Snate@binkert.org    all = []
4025517Snate@binkert.org
4035517Snate@binkert.org    def __init__(cls, name, bases, d):
4045517Snate@binkert.org        if not d.pop('abstract', False):
4055517Snate@binkert.org            ExecutableMeta.all.append(cls)
4065517Snate@binkert.org        super(ExecutableMeta, cls).__init__(name, bases, d)
4075517Snate@binkert.org
4085517Snate@binkert.org        cls.all = []
4095517Snate@binkert.org
4105517Snate@binkert.orgclass Executable(object):
4115517Snate@binkert.org    '''Base class for creating an executable from sources.'''
4125517Snate@binkert.org    __metaclass__ = ExecutableMeta
4135517Snate@binkert.org
4145517Snate@binkert.org    abstract = True
4156654Snate@binkert.org
4166654Snate@binkert.org    def __init__(self, target, *srcs_and_filts):
4175517Snate@binkert.org        '''Specify the target name and any sources. Sources that are
4185517Snate@binkert.org        not SourceFiles are evalued with Source().'''
4196143Snate@binkert.org        super(Executable, self).__init__()
4206143Snate@binkert.org        self.all.append(self)
4216143Snate@binkert.org        self.target = target
4226727Ssteve.reinhardt@amd.com
4235517Snate@binkert.org        isFilter = lambda arg: isinstance(arg, SourceFilter)
4246727Ssteve.reinhardt@amd.com        self.filters = filter(isFilter, srcs_and_filts)
4255517Snate@binkert.org        sources = filter(lambda a: not isFilter(a), srcs_and_filts)
4265517Snate@binkert.org
4275517Snate@binkert.org        srcs = SourceList()
4286654Snate@binkert.org        for src in sources:
4296654Snate@binkert.org            if not isinstance(src, SourceFile):
4307673Snate@binkert.org                src = Source(src, tags=[])
4316654Snate@binkert.org            srcs.append(src)
4326654Snate@binkert.org
4336654Snate@binkert.org        self.sources = srcs
4346654Snate@binkert.org        self.dir = Dir('.')
4355517Snate@binkert.org
4365517Snate@binkert.org    def path(self, env):
4375517Snate@binkert.org        return self.dir.File(self.target + '.' + env['EXE_SUFFIX'])
4386143Snate@binkert.org
4395517Snate@binkert.org    def srcs_to_objs(self, env, sources):
4404762Snate@binkert.org        return list([ s.static(env) for s in sources ])
4415517Snate@binkert.org
4425517Snate@binkert.org    @classmethod
4436143Snate@binkert.org    def declare_all(cls, env):
4446143Snate@binkert.org        return list([ instance.declare(env) for instance in cls.all ])
4455517Snate@binkert.org
4465517Snate@binkert.org    def declare(self, env, objs=None):
4475517Snate@binkert.org        if objs is None:
4485517Snate@binkert.org            objs = self.srcs_to_objs(env, self.sources)
4495517Snate@binkert.org
4505517Snate@binkert.org        env = env.Clone()
4515517Snate@binkert.org        env['BIN_RPATH_PREFIX'] = os.path.relpath(
4525517Snate@binkert.org                env['BUILDDIR'], self.path(env).dir.abspath)
4535517Snate@binkert.org
4548596Ssteve.reinhardt@amd.com        if env['STRIP_EXES']:
4558596Ssteve.reinhardt@amd.com            stripped = self.path(env)
4568596Ssteve.reinhardt@amd.com            unstripped = env.File(str(stripped) + '.unstripped')
4578596Ssteve.reinhardt@amd.com            if sys.platform == 'sunos5':
4588596Ssteve.reinhardt@amd.com                cmd = 'cp $SOURCE $TARGET; strip $TARGET'
4598596Ssteve.reinhardt@amd.com            else:
4608596Ssteve.reinhardt@amd.com                cmd = 'strip $SOURCE -o $TARGET'
4616143Snate@binkert.org            env.Program(unstripped, objs)
4625517Snate@binkert.org            return env.Command(stripped, unstripped,
4636654Snate@binkert.org                               MakeAction(cmd, Transform("STRIP")))
4646654Snate@binkert.org        else:
4656654Snate@binkert.org            return env.Program(self.path(env), objs)
4666654Snate@binkert.org
4676654Snate@binkert.orgclass UnitTest(Executable):
4686654Snate@binkert.org    '''Create a UnitTest'''
4695517Snate@binkert.org    def __init__(self, target, *srcs_and_filts, **kwargs):
4705517Snate@binkert.org        super(UnitTest, self).__init__(target, *srcs_and_filts)
4715517Snate@binkert.org
4728596Ssteve.reinhardt@amd.com        self.main = kwargs.get('main', False)
4738596Ssteve.reinhardt@amd.com
4744762Snate@binkert.org    def declare(self, env):
4754762Snate@binkert.org        sources = list(self.sources)
4764762Snate@binkert.org        for f in self.filters:
4774762Snate@binkert.org            sources += Source.all.apply_filter(f)
4784762Snate@binkert.org        objs = self.srcs_to_objs(env, sources) + env['STATIC_OBJS']
4794762Snate@binkert.org        if self.main:
4807675Snate@binkert.org            objs += env['MAIN_OBJS']
4814762Snate@binkert.org        return super(UnitTest, self).declare(env, objs)
4824762Snate@binkert.org
4834762Snate@binkert.orgclass GTest(Executable):
4844762Snate@binkert.org    '''Create a unit test based on the google test framework.'''
4854382Sbinkertn@umich.edu    all = []
4864382Sbinkertn@umich.edu    def __init__(self, *srcs_and_filts, **kwargs):
4875517Snate@binkert.org        super(GTest, self).__init__(*srcs_and_filts)
4886654Snate@binkert.org
4895517Snate@binkert.org        self.skip_lib = kwargs.pop('skip_lib', False)
4908126Sgblack@eecs.umich.edu
4916654Snate@binkert.org    @classmethod
4927673Snate@binkert.org    def declare_all(cls, env):
4936654Snate@binkert.org        env = env.Clone()
4946654Snate@binkert.org        env.Append(LIBS=env['GTEST_LIBS'])
4956654Snate@binkert.org        env.Append(CPPFLAGS=env['GTEST_CPPFLAGS'])
4966654Snate@binkert.org        env['GTEST_LIB_SOURCES'] = Source.all.with_tag('gtest lib')
4976654Snate@binkert.org        env['GTEST_OUT_DIR'] = \
4986654Snate@binkert.org            Dir(env['BUILDDIR']).Dir('unittests.' + env['EXE_SUFFIX'])
4996654Snate@binkert.org        return super(GTest, cls).declare_all(env)
5006669Snate@binkert.org
5016669Snate@binkert.org    def declare(self, env):
5026669Snate@binkert.org        sources = list(self.sources)
5036669Snate@binkert.org        if not self.skip_lib:
5046669Snate@binkert.org            sources += env['GTEST_LIB_SOURCES']
5056669Snate@binkert.org        for f in self.filters:
5066654Snate@binkert.org            sources += Source.all.apply_filter(f)
5077673Snate@binkert.org        objs = self.srcs_to_objs(env, sources)
5085517Snate@binkert.org
5098126Sgblack@eecs.umich.edu        binary = super(GTest, self).declare(env, objs)
5105798Snate@binkert.org
5117756SAli.Saidi@ARM.com        out_dir = env['GTEST_OUT_DIR']
5127816Ssteve.reinhardt@amd.com        xml_file = out_dir.Dir(str(self.dir)).File(self.target + '.xml')
5135798Snate@binkert.org        AlwaysBuild(env.Command(xml_file, binary,
5145798Snate@binkert.org            "${SOURCES[0]} --gtest_output=xml:${TARGETS[0]}"))
5155517Snate@binkert.org
5165517Snate@binkert.org        return binary
5177673Snate@binkert.org
5185517Snate@binkert.orgclass Gem5(Executable):
5195517Snate@binkert.org    '''Create a gem5 executable.'''
5207673Snate@binkert.org
5217673Snate@binkert.org    def __init__(self, target):
5225517Snate@binkert.org        super(Gem5, self).__init__(target)
5235798Snate@binkert.org
5245798Snate@binkert.org    def declare(self, env):
5258333Snate@binkert.org        objs = env['MAIN_OBJS'] + env['STATIC_OBJS']
5267816Ssteve.reinhardt@amd.com        return super(Gem5, self).declare(env, objs)
5275798Snate@binkert.org
5285798Snate@binkert.org
5294762Snate@binkert.org# Children should have access
5304762Snate@binkert.orgExport('Blob')
5314762Snate@binkert.orgExport('GdbXml')
5324762Snate@binkert.orgExport('Source')
5334762Snate@binkert.orgExport('PySource')
5348596Ssteve.reinhardt@amd.comExport('SimObject')
5355517Snate@binkert.orgExport('ProtoBuf')
5365517Snate@binkert.orgExport('Executable')
5375517Snate@binkert.orgExport('UnitTest')
5385517Snate@binkert.orgExport('GTest')
5395517Snate@binkert.org
5407673Snate@binkert.org########################################################################
5418596Ssteve.reinhardt@amd.com#
5427673Snate@binkert.org# Debug Flags
5435517Snate@binkert.org#
5448596Ssteve.reinhardt@amd.comdebug_flags = {}
5455517Snate@binkert.orgdef DebugFlag(name, desc=None):
5465517Snate@binkert.org    if name in debug_flags:
5475517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
5488596Ssteve.reinhardt@amd.com    debug_flags[name] = (name, (), desc)
5495517Snate@binkert.org
5507673Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
5517673Snate@binkert.org    if name in debug_flags:
5527673Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
5535517Snate@binkert.org
5545517Snate@binkert.org    compound = tuple(flags)
5555517Snate@binkert.org    debug_flags[name] = (name, compound, desc)
5565517Snate@binkert.org
5575517Snate@binkert.orgExport('DebugFlag')
5585517Snate@binkert.orgExport('CompoundFlag')
5595517Snate@binkert.org
5607673Snate@binkert.org########################################################################
5617673Snate@binkert.org#
5627673Snate@binkert.org# Set some compiler variables
5635517Snate@binkert.org#
5648596Ssteve.reinhardt@amd.com
5655517Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
5665517Snate@binkert.org# automatically expand '.' to refer to both the source directory and
5675517Snate@binkert.org# the corresponding build directory to pick up generated include
5685517Snate@binkert.org# files.
5695517Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
5707673Snate@binkert.org
5717673Snate@binkert.orgfor extra_dir in extras_dir_list:
5727673Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
5735517Snate@binkert.org
5748596Ssteve.reinhardt@amd.com# Workaround for bug in SCons version > 0.97d20071212
5757675Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
5767675Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
5777675Snate@binkert.org    Dir(root[len(base_dir) + 1:])
5787675Snate@binkert.org
5797675Snate@binkert.org########################################################################
5807675Snate@binkert.org#
5818596Ssteve.reinhardt@amd.com# Walk the tree and execute all SConscripts in subdirectories
5827675Snate@binkert.org#
5837675Snate@binkert.org
5848596Ssteve.reinhardt@amd.comhere = Dir('.').srcnode().abspath
5858596Ssteve.reinhardt@amd.comfor root, dirs, files in os.walk(base_dir, topdown=True):
5868596Ssteve.reinhardt@amd.com    if root == here:
5878596Ssteve.reinhardt@amd.com        # we don't want to recurse back into this SConscript
5888596Ssteve.reinhardt@amd.com        continue
5898596Ssteve.reinhardt@amd.com
5908596Ssteve.reinhardt@amd.com    if 'SConscript' in files:
5918596Ssteve.reinhardt@amd.com        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
5928596Ssteve.reinhardt@amd.com        Source.set_group(build_dir)
5934762Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
5946143Snate@binkert.org
5956143Snate@binkert.orgfor extra_dir in extras_dir_list:
5966143Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
5974762Snate@binkert.org
5984762Snate@binkert.org    # Also add the corresponding build directory to pick up generated
5994762Snate@binkert.org    # include files.
6007756SAli.Saidi@ARM.com    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
6018596Ssteve.reinhardt@amd.com
6024762Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
6034762Snate@binkert.org        # if build lives in the extras directory, don't walk down it
6048596Ssteve.reinhardt@amd.com        if 'build' in dirs:
6055463Snate@binkert.org            dirs.remove('build')
6068596Ssteve.reinhardt@amd.com
6078596Ssteve.reinhardt@amd.com        if 'SConscript' in files:
6085463Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
6097756SAli.Saidi@ARM.com            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
6108596Ssteve.reinhardt@amd.com
6114762Snate@binkert.orgfor opt in export_vars:
6127677Snate@binkert.org    env.ConfigFile(opt)
6134762Snate@binkert.org
6144762Snate@binkert.orgdef makeTheISA(source, target, env):
6156143Snate@binkert.org    isas = [ src.get_contents() for src in source ]
6166143Snate@binkert.org    target_isa = env['TARGET_ISA']
6176143Snate@binkert.org    def define(isa):
6184762Snate@binkert.org        return isa.upper() + '_ISA'
6194762Snate@binkert.org
6207756SAli.Saidi@ARM.com    def namespace(isa):
6217816Ssteve.reinhardt@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
6224762Snate@binkert.org
6234762Snate@binkert.org
6244762Snate@binkert.org    code = code_formatter()
6254762Snate@binkert.org    code('''\
6267756SAli.Saidi@ARM.com#ifndef __CONFIG_THE_ISA_HH__
6278596Ssteve.reinhardt@amd.com#define __CONFIG_THE_ISA_HH__
6284762Snate@binkert.org
6294762Snate@binkert.org''')
6307677Snate@binkert.org
6317756SAli.Saidi@ARM.com    # create defines for the preprocessing and compile-time determination
6328596Ssteve.reinhardt@amd.com    for i,isa in enumerate(isas):
6337675Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
6347677Snate@binkert.org    code()
6355517Snate@binkert.org
6368596Ssteve.reinhardt@amd.com    # create an enum for any run-time determination of the ISA, we
6377675Snate@binkert.org    # reuse the same name as the namespaces
6388596Ssteve.reinhardt@amd.com    code('enum class Arch {')
6398596Ssteve.reinhardt@amd.com    for i,isa in enumerate(isas):
6408596Ssteve.reinhardt@amd.com        if i + 1 == len(isas):
6418596Ssteve.reinhardt@amd.com            code('  $0 = $1', namespace(isa), define(isa))
6428596Ssteve.reinhardt@amd.com        else:
6434762Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
6447674Snate@binkert.org    code('};')
6457674Snate@binkert.org
6467674Snate@binkert.org    code('''
6477674Snate@binkert.org
6487674Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
6497674Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
6507674Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
6517674Snate@binkert.org
6527674Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
6537674Snate@binkert.org
6547674Snate@binkert.org    code.write(str(target[0]))
6557674Snate@binkert.org
6567674Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
6577674Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
6587674Snate@binkert.org
6594762Snate@binkert.orgdef makeTheGPUISA(source, target, env):
6606143Snate@binkert.org    isas = [ src.get_contents() for src in source ]
6616143Snate@binkert.org    target_gpu_isa = env['TARGET_GPU_ISA']
6627756SAli.Saidi@ARM.com    def define(isa):
6637816Ssteve.reinhardt@amd.com        return isa.upper() + '_ISA'
6648235Snate@binkert.org
6658596Ssteve.reinhardt@amd.com    def namespace(isa):
6667756SAli.Saidi@ARM.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
6677816Ssteve.reinhardt@amd.com
6688235Snate@binkert.org
6694382Sbinkertn@umich.edu    code = code_formatter()
6708232Snate@binkert.org    code('''\
6718232Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
6728232Snate@binkert.org#define __CONFIG_THE_GPU_ISA_HH__
6738232Snate@binkert.org
6748232Snate@binkert.org''')
6756229Snate@binkert.org
6768232Snate@binkert.org    # create defines for the preprocessing and compile-time determination
6778232Snate@binkert.org    for i,isa in enumerate(isas):
6788232Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
6796229Snate@binkert.org    code()
6807673Snate@binkert.org
6815517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
6825517Snate@binkert.org    # reuse the same name as the namespaces
6837673Snate@binkert.org    code('enum class GPUArch {')
6845517Snate@binkert.org    for i,isa in enumerate(isas):
6855517Snate@binkert.org        if i + 1 == len(isas):
6865517Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
6875517Snate@binkert.org        else:
6888232Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
6897673Snate@binkert.org    code('};')
6907673Snate@binkert.org
6918232Snate@binkert.org    code('''
6928232Snate@binkert.org
6938232Snate@binkert.org#define THE_GPU_ISA ${{define(target_gpu_isa)}}
6948232Snate@binkert.org#define TheGpuISA ${{namespace(target_gpu_isa)}}
6957673Snate@binkert.org#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
6965517Snate@binkert.org
6978232Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
6988232Snate@binkert.org
6998232Snate@binkert.org    code.write(str(target[0]))
7008232Snate@binkert.org
7017673Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
7028232Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
7038232Snate@binkert.org
7048232Snate@binkert.org########################################################################
7058232Snate@binkert.org#
7068232Snate@binkert.org# Prevent any SimObjects from being added after this point, they
7078232Snate@binkert.org# should all have been added in the SConscripts above
7087673Snate@binkert.org#
7095517Snate@binkert.orgSimObject.fixed = True
7108232Snate@binkert.org
7118232Snate@binkert.orgclass DictImporter(object):
7125517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
7137673Snate@binkert.org    map to arbitrary filenames.'''
7145517Snate@binkert.org    def __init__(self, modules):
7158232Snate@binkert.org        self.modules = modules
7168232Snate@binkert.org        self.installed = set()
7175517Snate@binkert.org
7188232Snate@binkert.org    def __del__(self):
7198232Snate@binkert.org        self.unload()
7208232Snate@binkert.org
7217673Snate@binkert.org    def unload(self):
7225517Snate@binkert.org        import sys
7235517Snate@binkert.org        for module in self.installed:
7247673Snate@binkert.org            del sys.modules[module]
7255517Snate@binkert.org        self.installed = set()
7265517Snate@binkert.org
7275517Snate@binkert.org    def find_module(self, fullname, path):
7288232Snate@binkert.org        if fullname == 'm5.defines':
7295517Snate@binkert.org            return self
7305517Snate@binkert.org
7318232Snate@binkert.org        if fullname == 'm5.objects':
7328232Snate@binkert.org            return self
7335517Snate@binkert.org
7348232Snate@binkert.org        if fullname.startswith('_m5'):
7358232Snate@binkert.org            return None
7365517Snate@binkert.org
7378232Snate@binkert.org        source = self.modules.get(fullname, None)
7388232Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
7398232Snate@binkert.org            return self
7405517Snate@binkert.org
7418232Snate@binkert.org        return None
7428232Snate@binkert.org
7438232Snate@binkert.org    def load_module(self, fullname):
7448232Snate@binkert.org        mod = imp.new_module(fullname)
7458232Snate@binkert.org        sys.modules[fullname] = mod
7468232Snate@binkert.org        self.installed.add(fullname)
7475517Snate@binkert.org
7488232Snate@binkert.org        mod.__loader__ = self
7498232Snate@binkert.org        if fullname == 'm5.objects':
7505517Snate@binkert.org            mod.__path__ = fullname.split('.')
7518232Snate@binkert.org            return mod
7527673Snate@binkert.org
7535517Snate@binkert.org        if fullname == 'm5.defines':
7547673Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
7555517Snate@binkert.org            return mod
7568232Snate@binkert.org
7578232Snate@binkert.org        source = self.modules[fullname]
7588232Snate@binkert.org        if source.modname == '__init__':
7595192Ssaidi@eecs.umich.edu            mod.__path__ = source.modpath
7608232Snate@binkert.org        mod.__file__ = source.abspath
7618232Snate@binkert.org
7628232Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
7638232Snate@binkert.org
7648232Snate@binkert.org        return mod
7655192Ssaidi@eecs.umich.edu
7667674Snate@binkert.orgimport m5.SimObject
7675522Snate@binkert.orgimport m5.params
7685522Snate@binkert.orgfrom m5.util import code_formatter
7697674Snate@binkert.org
7707674Snate@binkert.orgm5.SimObject.clear()
7717674Snate@binkert.orgm5.params.clear()
7727674Snate@binkert.org
7737674Snate@binkert.org# install the python importer so we can grab stuff from the source
7747674Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
7757674Snate@binkert.org# else we won't know about them for the rest of the stuff.
7767674Snate@binkert.orgimporter = DictImporter(PySource.modules)
7775522Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
7785522Snate@binkert.org
7795522Snate@binkert.org# import all sim objects so we can populate the all_objects list
7805517Snate@binkert.org# make sure that we're working with a list, then let's sort it
7815522Snate@binkert.orgfor modname in SimObject.modnames:
7825517Snate@binkert.org    exec('from m5.objects import %s' % modname)
7836143Snate@binkert.org
7846727Ssteve.reinhardt@amd.com# we need to unload all of the currently imported modules so that they
7855522Snate@binkert.org# will be re-imported the next time the sconscript is run
7865522Snate@binkert.orgimporter.unload()
7875522Snate@binkert.orgsys.meta_path.remove(importer)
7887674Snate@binkert.org
7895517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
7907673Snate@binkert.orgall_enums = m5.params.allEnums
7917673Snate@binkert.org
7927674Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
7937673Snate@binkert.org    for param in obj._params.local.values():
7947674Snate@binkert.org        # load the ptype attribute now because it depends on the
7957674Snate@binkert.org        # current version of SimObject.allClasses, but when scons
7968946Sandreas.hansson@arm.com        # actually uses the value, all versions of
7977674Snate@binkert.org        # SimObject.allClasses will have been loaded
7987674Snate@binkert.org        param.ptype
7997674Snate@binkert.org
8005522Snate@binkert.org########################################################################
8015522Snate@binkert.org#
8027674Snate@binkert.org# calculate extra dependencies
8037674Snate@binkert.org#
8047674Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
8057674Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
8067673Snate@binkert.orgdepends.sort(key = lambda x: x.name)
8077674Snate@binkert.org
8087674Snate@binkert.org########################################################################
8097674Snate@binkert.org#
8107674Snate@binkert.org# Commands for the basic automatically generated python files
8117674Snate@binkert.org#
8127674Snate@binkert.org
8137674Snate@binkert.org# Generate Python file containing a dict specifying the current
8147674Snate@binkert.org# buildEnv flags.
8157811Ssteve.reinhardt@amd.comdef makeDefinesPyFile(target, source, env):
8167674Snate@binkert.org    build_env = source[0].get_contents()
8177673Snate@binkert.org
8185522Snate@binkert.org    code = code_formatter()
8196143Snate@binkert.org    code("""
8207756SAli.Saidi@ARM.comimport _m5.core
8217816Ssteve.reinhardt@amd.comimport m5.util
8227674Snate@binkert.org
8234382Sbinkertn@umich.edubuildEnv = m5.util.SmartDict($build_env)
8244382Sbinkertn@umich.edu
8254382Sbinkertn@umich.educompileDate = _m5.core.compileDate
8264382Sbinkertn@umich.edu_globals = globals()
8274382Sbinkertn@umich.edufor key,val in _m5.core.__dict__.items():
8284382Sbinkertn@umich.edu    if key.startswith('flag_'):
8294382Sbinkertn@umich.edu        flag = key[5:]
8304382Sbinkertn@umich.edu        _globals[flag] = val
8314382Sbinkertn@umich.edudel _globals
8324382Sbinkertn@umich.edu""")
8336143Snate@binkert.org    code.write(target[0].abspath)
834955SN/A
8352655Sstever@eecs.umich.edudefines_info = Value(build_env)
8362655Sstever@eecs.umich.edu# Generate a file with all of the compile options in it
8372655Sstever@eecs.umich.eduenv.Command('python/m5/defines.py', defines_info,
8382655Sstever@eecs.umich.edu            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
8392655Sstever@eecs.umich.eduPySource('m5', 'python/m5/defines.py')
8405601Snate@binkert.org
8415601Snate@binkert.org# Generate python file containing info about the M5 source code
8428334Snate@binkert.orgdef makeInfoPyFile(target, source, env):
8438334Snate@binkert.org    code = code_formatter()
8448334Snate@binkert.org    for src in source:
8455522Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
8465863Snate@binkert.org        code('$src = ${{repr(data)}}')
8475601Snate@binkert.org    code.write(str(target[0]))
8485601Snate@binkert.org
8495601Snate@binkert.org# Generate a file that wraps the basic top level files
8505863Snate@binkert.orgenv.Command('python/m5/info.py',
8518945Ssteve.reinhardt@amd.com            [ '#/COPYING', '#/LICENSE', '#/README', ],
8525559Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
8539175Sandreas.hansson@arm.comPySource('m5', 'python/m5/info.py')
8549175Sandreas.hansson@arm.com
8559175Sandreas.hansson@arm.com########################################################################
8568946Sandreas.hansson@arm.com#
8578614Sgblack@eecs.umich.edu# Create all of the SimObject param headers and enum headers
8588737Skoansin.tan@gmail.com#
8599175Sandreas.hansson@arm.com
8608945Ssteve.reinhardt@amd.comdef createSimObjectParamStruct(target, source, env):
8618945Ssteve.reinhardt@amd.com    assert len(target) == 1 and len(source) == 1
8628945Ssteve.reinhardt@amd.com
8638945Ssteve.reinhardt@amd.com    name = source[0].get_text_contents()
8646143Snate@binkert.org    obj = sim_objects[name]
8656143Snate@binkert.org
8666143Snate@binkert.org    code = code_formatter()
8676143Snate@binkert.org    obj.cxx_param_decl(code)
8686143Snate@binkert.org    code.write(target[0].abspath)
8696143Snate@binkert.org
8706143Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
8718945Ssteve.reinhardt@amd.com    def body(target, source, env):
8728945Ssteve.reinhardt@amd.com        assert len(target) == 1 and len(source) == 1
8736143Snate@binkert.org
8746143Snate@binkert.org        name = str(source[0].get_contents())
8756143Snate@binkert.org        obj = sim_objects[name]
8766143Snate@binkert.org
8776143Snate@binkert.org        code = code_formatter()
8786143Snate@binkert.org        obj.cxx_config_param_file(code, is_header)
8796143Snate@binkert.org        code.write(target[0].abspath)
8806143Snate@binkert.org    return body
8816143Snate@binkert.org
8826143Snate@binkert.orgdef createEnumStrings(target, source, env):
8836143Snate@binkert.org    assert len(target) == 1 and len(source) == 2
8846143Snate@binkert.org
8856143Snate@binkert.org    name = source[0].get_text_contents()
8868594Snate@binkert.org    use_python = source[1].read()
8878594Snate@binkert.org    obj = all_enums[name]
8888594Snate@binkert.org
8898594Snate@binkert.org    code = code_formatter()
8906143Snate@binkert.org    obj.cxx_def(code)
8916143Snate@binkert.org    if use_python:
8926143Snate@binkert.org        obj.pybind_def(code)
8936143Snate@binkert.org    code.write(target[0].abspath)
8946143Snate@binkert.org
8956240Snate@binkert.orgdef createEnumDecls(target, source, env):
8965554Snate@binkert.org    assert len(target) == 1 and len(source) == 1
8975522Snate@binkert.org
8985522Snate@binkert.org    name = source[0].get_text_contents()
8995797Snate@binkert.org    obj = all_enums[name]
9005797Snate@binkert.org
9015522Snate@binkert.org    code = code_formatter()
9025601Snate@binkert.org    obj.cxx_decl(code)
9038233Snate@binkert.org    code.write(target[0].abspath)
9048233Snate@binkert.org
9058235Snate@binkert.orgdef createSimObjectPyBindWrapper(target, source, env):
9068235Snate@binkert.org    name = source[0].get_text_contents()
9078235Snate@binkert.org    obj = sim_objects[name]
9088235Snate@binkert.org
9099003SAli.Saidi@ARM.com    code = code_formatter()
9109003SAli.Saidi@ARM.com    obj.pybind_decl(code)
9118235Snate@binkert.org    code.write(target[0].abspath)
9128942Sgblack@eecs.umich.edu
9138235Snate@binkert.org# Generate all of the SimObject param C++ struct header files
9146143Snate@binkert.orgparams_hh_files = []
9152655Sstever@eecs.umich.edufor name,simobj in sorted(sim_objects.iteritems()):
9166143Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
9176143Snate@binkert.org    extra_deps = [ py_source.tnode ]
9188233Snate@binkert.org
9196143Snate@binkert.org    hh_file = File('params/%s.hh' % name)
9206143Snate@binkert.org    params_hh_files.append(hh_file)
9214007Ssaidi@eecs.umich.edu    env.Command(hh_file, Value(name),
9224596Sbinkertn@umich.edu                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
9234007Ssaidi@eecs.umich.edu    env.Depends(hh_file, depends + extra_deps)
9244596Sbinkertn@umich.edu
9257756SAli.Saidi@ARM.com# C++ parameter description files
9267816Ssteve.reinhardt@amd.comif GetOption('with_cxx_config'):
9278334Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
9288334Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
9298334Snate@binkert.org        extra_deps = [ py_source.tnode ]
9308334Snate@binkert.org
9315601Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
9325601Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
9332655Sstever@eecs.umich.edu        env.Command(cxx_config_hh_file, Value(name),
9349225Sandreas.hansson@arm.com                    MakeAction(createSimObjectCxxConfig(True),
9359225Sandreas.hansson@arm.com                    Transform("CXXCPRHH")))
9369226Sandreas.hansson@arm.com        env.Command(cxx_config_cc_file, Value(name),
9379226Sandreas.hansson@arm.com                    MakeAction(createSimObjectCxxConfig(False),
9389225Sandreas.hansson@arm.com                    Transform("CXXCPRCC")))
9399226Sandreas.hansson@arm.com        env.Depends(cxx_config_hh_file, depends + extra_deps +
9409226Sandreas.hansson@arm.com                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
9419226Sandreas.hansson@arm.com        env.Depends(cxx_config_cc_file, depends + extra_deps +
9429226Sandreas.hansson@arm.com                    [cxx_config_hh_file])
9439226Sandreas.hansson@arm.com        Source(cxx_config_cc_file)
9449226Sandreas.hansson@arm.com
9459225Sandreas.hansson@arm.com    cxx_config_init_cc_file = File('cxx_config/init.cc')
9468946Sandreas.hansson@arm.com
9473918Ssaidi@eecs.umich.edu    def createCxxConfigInitCC(target, source, env):
9489225Sandreas.hansson@arm.com        assert len(target) == 1 and len(source) == 1
9493918Ssaidi@eecs.umich.edu
9509225Sandreas.hansson@arm.com        code = code_formatter()
9519225Sandreas.hansson@arm.com
9529226Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
9539226Sandreas.hansson@arm.com            if not hasattr(simobj, 'abstract') or not simobj.abstract:
9549225Sandreas.hansson@arm.com                code('#include "cxx_config/${name}.hh"')
9553918Ssaidi@eecs.umich.edu        code()
9569225Sandreas.hansson@arm.com        code('void cxxConfigInit()')
9579225Sandreas.hansson@arm.com        code('{')
9589226Sandreas.hansson@arm.com        code.indent()
9599226Sandreas.hansson@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
9603940Ssaidi@eecs.umich.edu            not_abstract = not hasattr(simobj, 'abstract') or \
9619225Sandreas.hansson@arm.com                not simobj.abstract
9629225Sandreas.hansson@arm.com            if not_abstract and 'type' in simobj.__dict__:
9639226Sandreas.hansson@arm.com                code('cxx_config_directory["${name}"] = '
9649226Sandreas.hansson@arm.com                     '${name}CxxConfigParams::makeDirectoryEntry();')
9658946Sandreas.hansson@arm.com        code.dedent()
9669225Sandreas.hansson@arm.com        code('}')
9679226Sandreas.hansson@arm.com        code.write(target[0].abspath)
9689226Sandreas.hansson@arm.com
9699226Sandreas.hansson@arm.com    py_source = PySource.modules[simobj.__module__]
9703515Ssaidi@eecs.umich.edu    extra_deps = [ py_source.tnode ]
9713918Ssaidi@eecs.umich.edu    env.Command(cxx_config_init_cc_file, Value(name),
9724762Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
9733515Ssaidi@eecs.umich.edu    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
9748881Smarc.orr@gmail.com        for name,simobj in sorted(sim_objects.iteritems())
9758881Smarc.orr@gmail.com        if not hasattr(simobj, 'abstract') or not simobj.abstract]
9768881Smarc.orr@gmail.com    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
9778881Smarc.orr@gmail.com            [File('sim/cxx_config.hh')])
9788881Smarc.orr@gmail.com    Source(cxx_config_init_cc_file)
9799226Sandreas.hansson@arm.com
9809226Sandreas.hansson@arm.com# Generate all enum header files
9819226Sandreas.hansson@arm.comfor name,enum in sorted(all_enums.iteritems()):
9828881Smarc.orr@gmail.com    py_source = PySource.modules[enum.__module__]
9838881Smarc.orr@gmail.com    extra_deps = [ py_source.tnode ]
9848881Smarc.orr@gmail.com
9858881Smarc.orr@gmail.com    cc_file = File('enums/%s.cc' % name)
9868881Smarc.orr@gmail.com    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
9878881Smarc.orr@gmail.com                MakeAction(createEnumStrings, Transform("ENUM STR")))
9888881Smarc.orr@gmail.com    env.Depends(cc_file, depends + extra_deps)
9898881Smarc.orr@gmail.com    Source(cc_file)
9908881Smarc.orr@gmail.com
9918881Smarc.orr@gmail.com    hh_file = File('enums/%s.hh' % name)
9928881Smarc.orr@gmail.com    env.Command(hh_file, Value(name),
9938881Smarc.orr@gmail.com                MakeAction(createEnumDecls, Transform("ENUMDECL")))
9948881Smarc.orr@gmail.com    env.Depends(hh_file, depends + extra_deps)
9958881Smarc.orr@gmail.com
9968881Smarc.orr@gmail.com# Generate SimObject Python bindings wrapper files
9978881Smarc.orr@gmail.comif env['USE_PYTHON']:
9988881Smarc.orr@gmail.com    for name,simobj in sorted(sim_objects.iteritems()):
9998881Smarc.orr@gmail.com        py_source = PySource.modules[simobj.__module__]
10008881Smarc.orr@gmail.com        extra_deps = [ py_source.tnode ]
10018881Smarc.orr@gmail.com        cc_file = File('python/_m5/param_%s.cc' % name)
10029225Sandreas.hansson@arm.com        env.Command(cc_file, Value(name),
10039225Sandreas.hansson@arm.com                    MakeAction(createSimObjectPyBindWrapper,
1004955SN/A                               Transform("SO PyBind")))
1005955SN/A        env.Depends(cc_file, depends + extra_deps)
10068881Smarc.orr@gmail.com        Source(cc_file)
10078881Smarc.orr@gmail.com
10088881Smarc.orr@gmail.com# Build all protocol buffers if we have got protoc and protobuf available
10099225Sandreas.hansson@arm.comif env['HAVE_PROTOBUF']:
10109225Sandreas.hansson@arm.com    for proto in ProtoBuf.all:
1011955SN/A        # Use both the source and header as the target, and the .proto
1012955SN/A        # file as the source. When executing the protoc compiler, also
10138881Smarc.orr@gmail.com        # specify the proto_path to avoid having the generated files
10148881Smarc.orr@gmail.com        # include the path.
10158881Smarc.orr@gmail.com        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
10169225Sandreas.hansson@arm.com                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
10179225Sandreas.hansson@arm.com                               '--proto_path ${SOURCE.dir} $SOURCE',
1018955SN/A                               Transform("PROTOC")))
10199226Sandreas.hansson@arm.com
10208881Smarc.orr@gmail.com        # Add the C++ source file
10218881Smarc.orr@gmail.com        Source(proto.cc_file, tags=proto.tags)
10228881Smarc.orr@gmail.comelif ProtoBuf.all:
10238881Smarc.orr@gmail.com    print('Got protobuf to build, but lacks support!')
10249225Sandreas.hansson@arm.com    Exit(1)
10251869SN/A
10269226Sandreas.hansson@arm.com#
10279226Sandreas.hansson@arm.com# Handle debug flags
10289226Sandreas.hansson@arm.com#
10299226Sandreas.hansson@arm.comdef makeDebugFlagCC(target, source, env):
10309226Sandreas.hansson@arm.com    assert(len(target) == 1 and len(source) == 1)
10319226Sandreas.hansson@arm.com
10329226Sandreas.hansson@arm.com    code = code_formatter()
10331869SN/A
1034    # delay definition of CompoundFlags until after all the definition
1035    # of all constituent SimpleFlags
1036    comp_code = code_formatter()
1037
1038    # file header
1039    code('''
1040/*
1041 * DO NOT EDIT THIS FILE! Automatically generated by SCons.
1042 */
1043
1044#include "base/debug.hh"
1045
1046namespace Debug {
1047
1048''')
1049
1050    for name, flag in sorted(source[0].read().iteritems()):
1051        n, compound, desc = flag
1052        assert n == name
1053
1054        if not compound:
1055            code('SimpleFlag $name("$name", "$desc");')
1056        else:
1057            comp_code('CompoundFlag $name("$name", "$desc",')
1058            comp_code.indent()
1059            last = len(compound) - 1
1060            for i,flag in enumerate(compound):
1061                if i != last:
1062                    comp_code('&$flag,')
1063                else:
1064                    comp_code('&$flag);')
1065            comp_code.dedent()
1066
1067    code.append(comp_code)
1068    code()
1069    code('} // namespace Debug')
1070
1071    code.write(str(target[0]))
1072
1073def makeDebugFlagHH(target, source, env):
1074    assert(len(target) == 1 and len(source) == 1)
1075
1076    val = eval(source[0].get_contents())
1077    name, compound, desc = val
1078
1079    code = code_formatter()
1080
1081    # file header boilerplate
1082    code('''\
1083/*
1084 * DO NOT EDIT THIS FILE! Automatically generated by SCons.
1085 */
1086
1087#ifndef __DEBUG_${name}_HH__
1088#define __DEBUG_${name}_HH__
1089
1090namespace Debug {
1091''')
1092
1093    if compound:
1094        code('class CompoundFlag;')
1095    code('class SimpleFlag;')
1096
1097    if compound:
1098        code('extern CompoundFlag $name;')
1099        for flag in compound:
1100            code('extern SimpleFlag $flag;')
1101    else:
1102        code('extern SimpleFlag $name;')
1103
1104    code('''
1105}
1106
1107#endif // __DEBUG_${name}_HH__
1108''')
1109
1110    code.write(str(target[0]))
1111
1112for name,flag in sorted(debug_flags.iteritems()):
1113    n, compound, desc = flag
1114    assert n == name
1115
1116    hh_file = 'debug/%s.hh' % name
1117    env.Command(hh_file, Value(flag),
1118                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
1119
1120env.Command('debug/flags.cc', Value(debug_flags),
1121            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
1122Source('debug/flags.cc')
1123
1124# version tags
1125tags = \
1126env.Command('sim/tags.cc', None,
1127            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
1128                       Transform("VER TAGS")))
1129env.AlwaysBuild(tags)
1130
1131# Build a small helper that marshals the Python code using the same
1132# version of Python as gem5. This is in an unorthodox location to
1133# avoid building it for every variant.
1134py_marshal = env.Program('marshal', 'python/marshal.cc')[0]
1135
1136# Embed python files.  All .py files that have been indicated by a
1137# PySource() call in a SConscript need to be embedded into the M5
1138# library.  To do that, we compile the file to byte code, marshal the
1139# byte code, compress it, and then generate a c++ file that
1140# inserts the result into an array.
1141def embedPyFile(target, source, env):
1142    def c_str(string):
1143        if string is None:
1144            return "0"
1145        return '"%s"' % string
1146
1147    '''Action function to compile a .py into a code object, marshal it,
1148    compress it, and stick it into an asm file so the code appears as
1149    just bytes with a label in the data section. The action takes two
1150    sources:
1151
1152    source[0]: Binary used to marshal Python sources
1153    source[1]: Python script to marshal
1154    '''
1155
1156    import subprocess
1157
1158    marshalled = subprocess.check_output([source[0].abspath, str(source[1])])
1159
1160    compressed = zlib.compress(marshalled)
1161    data = compressed
1162    pysource = PySource.tnodes[source[1]]
1163    sym = pysource.symname
1164
1165    code = code_formatter()
1166    code('''\
1167#include "sim/init.hh"
1168
1169namespace {
1170
1171''')
1172    blobToCpp(data, 'data_' + sym, code)
1173    code('''\
1174
1175
1176EmbeddedPython embedded_${sym}(
1177    ${{c_str(pysource.arcname)}},
1178    ${{c_str(pysource.abspath)}},
1179    ${{c_str(pysource.modpath)}},
1180    data_${sym},
1181    ${{len(data)}},
1182    ${{len(marshalled)}});
1183
1184} // anonymous namespace
1185''')
1186    code.write(str(target[0]))
1187
1188for source in PySource.all:
1189    env.Command(source.cpp, [ py_marshal, source.tnode ],
1190                MakeAction(embedPyFile, Transform("EMBED PY")))
1191    Source(source.cpp, tags=source.tags, add_tags='python')
1192
1193########################################################################
1194#
1195# Define binaries.  Each different build type (debug, opt, etc.) gets
1196# a slightly different build environment.
1197#
1198
1199# List of constructed environments to pass back to SConstruct
1200date_source = Source('base/date.cc', tags=[])
1201
1202gem5_binary = Gem5('gem5')
1203
1204# Function to create a new build environment as clone of current
1205# environment 'env' with modified object suffix and optional stripped
1206# binary.  Additional keyword arguments are appended to corresponding
1207# build environment vars.
1208def makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
1209    # SCons doesn't know to append a library suffix when there is a '.' in the
1210    # name.  Use '_' instead.
1211    libname = 'gem5_' + label
1212    secondary_exename = 'm5.' + label
1213
1214    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
1215    new_env.Label = label
1216    new_env.Append(**kwargs)
1217
1218    lib_sources = Source.all.with_tag('gem5 lib')
1219
1220    # Without Python, leave out all Python content from the library
1221    # builds.  The option doesn't affect gem5 built as a program
1222    if GetOption('without_python'):
1223        lib_sources = lib_sources.without_tag('python')
1224
1225    static_objs = []
1226    shared_objs = []
1227
1228    for s in lib_sources.with_tag(Source.ungrouped_tag):
1229        static_objs.append(s.static(new_env))
1230        shared_objs.append(s.shared(new_env))
1231
1232    for group in Source.source_groups:
1233        srcs = lib_sources.with_tag(Source.link_group_tag(group))
1234        if not srcs:
1235            continue
1236
1237        group_static = [ s.static(new_env) for s in srcs ]
1238        group_shared = [ s.shared(new_env) for s in srcs ]
1239
1240        # If partial linking is disabled, add these sources to the build
1241        # directly, and short circuit this loop.
1242        if disable_partial:
1243            static_objs.extend(group_static)
1244            shared_objs.extend(group_shared)
1245            continue
1246
1247        # Set up the static partially linked objects.
1248        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
1249        target = File(joinpath(group, file_name))
1250        partial = env.PartialStatic(target=target, source=group_static)
1251        static_objs.extend(partial)
1252
1253        # Set up the shared partially linked objects.
1254        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
1255        target = File(joinpath(group, file_name))
1256        partial = env.PartialShared(target=target, source=group_shared)
1257        shared_objs.extend(partial)
1258
1259    static_date = date_source.static(new_env)
1260    new_env.Depends(static_date, static_objs)
1261    static_objs.extend(static_date)
1262
1263    shared_date = date_source.shared(new_env)
1264    new_env.Depends(shared_date, shared_objs)
1265    shared_objs.extend(shared_date)
1266
1267    main_objs = [ s.static(new_env) for s in Source.all.with_tag('main') ]
1268
1269    # First make a library of everything but main() so other programs can
1270    # link against m5.
1271    static_lib = new_env.StaticLibrary(libname, static_objs)
1272    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1273
1274    # Keep track of the object files generated so far so Executables can
1275    # include them.
1276    new_env['STATIC_OBJS'] = static_objs
1277    new_env['SHARED_OBJS'] = shared_objs
1278    new_env['MAIN_OBJS'] = main_objs
1279
1280    new_env['STATIC_LIB'] = static_lib
1281    new_env['SHARED_LIB'] = shared_lib
1282
1283    # Record some settings for building Executables.
1284    new_env['EXE_SUFFIX'] = label
1285    new_env['STRIP_EXES'] = strip
1286
1287    for cls in ExecutableMeta.all:
1288        cls.declare_all(new_env)
1289
1290    new_env.M5Binary = File(gem5_binary.path(new_env))
1291
1292    new_env.Command(secondary_exename, new_env.M5Binary,
1293            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1294
1295    # Set up regression tests.
1296    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1297               variant_dir=Dir('tests').Dir(new_env.Label),
1298               exports={ 'env' : new_env }, duplicate=False)
1299
1300# Start out with the compiler flags common to all compilers,
1301# i.e. they all use -g for opt and -g -pg for prof
1302ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1303           'perf' : ['-g']}
1304
1305# Start out with the linker flags common to all linkers, i.e. -pg for
1306# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1307# no-as-needed and as-needed as the binutils linker is too clever and
1308# simply doesn't link to the library otherwise.
1309ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1310           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1311
1312# For Link Time Optimization, the optimisation flags used to compile
1313# individual files are decoupled from those used at link time
1314# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1315# to also update the linker flags based on the target.
1316if env['GCC']:
1317    if sys.platform == 'sunos5':
1318        ccflags['debug'] += ['-gstabs+']
1319    else:
1320        ccflags['debug'] += ['-ggdb3']
1321    ldflags['debug'] += ['-O0']
1322    # opt, fast, prof and perf all share the same cc flags, also add
1323    # the optimization to the ldflags as LTO defers the optimization
1324    # to link time
1325    for target in ['opt', 'fast', 'prof', 'perf']:
1326        ccflags[target] += ['-O3']
1327        ldflags[target] += ['-O3']
1328
1329    ccflags['fast'] += env['LTO_CCFLAGS']
1330    ldflags['fast'] += env['LTO_LDFLAGS']
1331elif env['CLANG']:
1332    ccflags['debug'] += ['-g', '-O0']
1333    # opt, fast, prof and perf all share the same cc flags
1334    for target in ['opt', 'fast', 'prof', 'perf']:
1335        ccflags[target] += ['-O3']
1336else:
1337    print('Unknown compiler, please fix compiler options')
1338    Exit(1)
1339
1340
1341# To speed things up, we only instantiate the build environments we
1342# need.  We try to identify the needed environment for each target; if
1343# we can't, we fall back on instantiating all the environments just to
1344# be safe.
1345target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1346obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1347              'gpo' : 'perf'}
1348
1349def identifyTarget(t):
1350    ext = t.split('.')[-1]
1351    if ext in target_types:
1352        return ext
1353    if ext in obj2target:
1354        return obj2target[ext]
1355    match = re.search(r'/tests/([^/]+)/', t)
1356    if match and match.group(1) in target_types:
1357        return match.group(1)
1358    return 'all'
1359
1360needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1361if 'all' in needed_envs:
1362    needed_envs += target_types
1363
1364disable_partial = False
1365if env['PLATFORM'] == 'darwin':
1366    # Up until Apple LLVM version 10.0.0 (clang-1000.11.45.5), partial
1367    # linked objects do not expose symbols that are marked with the
1368    # hidden visibility and consequently building gem5 on Mac OS
1369    # fails. As a workaround, we disable partial linking, however, we
1370    # may want to revisit in the future.
1371    disable_partial = True
1372
1373# Debug binary
1374if 'debug' in needed_envs:
1375    makeEnv(env, 'debug', '.do',
1376            CCFLAGS = Split(ccflags['debug']),
1377            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1378            LINKFLAGS = Split(ldflags['debug']),
1379            disable_partial=disable_partial)
1380
1381# Optimized binary
1382if 'opt' in needed_envs:
1383    makeEnv(env, 'opt', '.o',
1384            CCFLAGS = Split(ccflags['opt']),
1385            CPPDEFINES = ['TRACING_ON=1'],
1386            LINKFLAGS = Split(ldflags['opt']),
1387            disable_partial=disable_partial)
1388
1389# "Fast" binary
1390if 'fast' in needed_envs:
1391    disable_partial = disable_partial or \
1392            (env.get('BROKEN_INCREMENTAL_LTO', False) and \
1393            GetOption('force_lto'))
1394    makeEnv(env, 'fast', '.fo', strip = True,
1395            CCFLAGS = Split(ccflags['fast']),
1396            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1397            LINKFLAGS = Split(ldflags['fast']),
1398            disable_partial=disable_partial)
1399
1400# Profiled binary using gprof
1401if 'prof' in needed_envs:
1402    makeEnv(env, 'prof', '.po',
1403            CCFLAGS = Split(ccflags['prof']),
1404            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1405            LINKFLAGS = Split(ldflags['prof']),
1406            disable_partial=disable_partial)
1407
1408# Profiled binary using google-pprof
1409if 'perf' in needed_envs:
1410    makeEnv(env, 'perf', '.gpo',
1411            CCFLAGS = Split(ccflags['perf']),
1412            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1413            LINKFLAGS = Split(ldflags['perf']),
1414            disable_partial=disable_partial)
1415