SConscript revision 5299
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# Redistribution and use in source and binary forms, with or without
7955SN/A# modification, are permitted provided that the following conditions are
8955SN/A# met: redistributions of source code must retain the above copyright
9955SN/A# notice, this list of conditions and the following disclaimer;
10955SN/A# redistributions in binary form must reproduce the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer in the
12955SN/A# documentation and/or other materials provided with the distribution;
13955SN/A# neither the name of the copyright holders nor the names of its
14955SN/A# contributors may be used to endorse or promote products derived from
15955SN/A# this software without specific prior written permission.
16955SN/A#
17955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
292665Ssaidi@eecs.umich.edu# Authors: Nathan Binkert
30955SN/A
31955SN/Aimport imp
32955SN/Aimport os
334202Sbinkertn@umich.eduimport sys
344202Sbinkertn@umich.edu
35955SN/Afrom os.path import basename
36955SN/Afrom os.path import join as joinpath
37955SN/Afrom os.path import exists
38955SN/Afrom os.path import isdir
394202Sbinkertn@umich.edufrom os.path import isfile
40955SN/A
414202Sbinkertn@umich.eduimport SCons
424202Sbinkertn@umich.edu
434202Sbinkertn@umich.edu# This file defines how to build a particular configuration of M5
444202Sbinkertn@umich.edu# based on variable settings in the 'env' build environment.
454202Sbinkertn@umich.edu
464202Sbinkertn@umich.eduImport('*')
474202Sbinkertn@umich.edu
484202Sbinkertn@umich.edu# Children need to see the environment
494202Sbinkertn@umich.eduExport('env')
504202Sbinkertn@umich.edu
51955SN/Adef sort_list(_list):
524202Sbinkertn@umich.edu    """return a sorted copy of '_list'"""
534202Sbinkertn@umich.edu    if isinstance(_list, list):
54955SN/A        _list = _list[:]
552667Sstever@eecs.umich.edu    else:
562667Sstever@eecs.umich.edu        _list = list(_list)
572667Sstever@eecs.umich.edu    _list.sort()
582667Sstever@eecs.umich.edu    return _list
592667Sstever@eecs.umich.edu
602667Sstever@eecs.umich.educlass PySourceFile(object):
612037SN/A    def __init__(self, package, source):
622037SN/A        filename = str(source)
632037SN/A        pyname = basename(filename)
644202Sbinkertn@umich.edu        assert pyname.endswith('.py')
654202Sbinkertn@umich.edu        name = pyname[:-3]
664202Sbinkertn@umich.edu        path = package.split('.')
674202Sbinkertn@umich.edu        modpath = path
684202Sbinkertn@umich.edu        if name != '__init__':
694202Sbinkertn@umich.edu            modpath += [name]
704202Sbinkertn@umich.edu        modpath = '.'.join(modpath)
714202Sbinkertn@umich.edu
724202Sbinkertn@umich.edu        arcpath = package.split('.') + [ pyname + 'c' ]
734202Sbinkertn@umich.edu        arcname = joinpath(*arcpath)
744202Sbinkertn@umich.edu
754202Sbinkertn@umich.edu        self.source = source
764202Sbinkertn@umich.edu        self.pyname = pyname
771858SN/A        self.srcpath = source.srcnode().abspath
781858SN/A        self.package = package
791858SN/A        self.modpath = modpath
801085SN/A        self.arcname = arcname
81955SN/A        self.filename = filename
82955SN/A        self.compiled = File(filename + 'c')
83955SN/A
84955SN/A########################################################################
851108SN/A# Code for adding source files of various types
86955SN/A#
87955SN/Acc_sources = []
88955SN/Adef Source(source):
89955SN/A    '''Add a C/C++ source file to the build'''
90955SN/A    if not isinstance(source, SCons.Node.FS.File):
91955SN/A        source = File(source)
92955SN/A
93955SN/A    cc_sources.append(source)
94955SN/A
95955SN/Apy_sources = []
96955SN/Adef PySource(package, source):
97955SN/A    '''Add a python source file to the named package'''
98955SN/A    if not isinstance(source, SCons.Node.FS.File):
99955SN/A        source = File(source)
100955SN/A
101955SN/A    source = PySourceFile(package, source)
1022655Sstever@eecs.umich.edu    py_sources.append(source)
1032655Sstever@eecs.umich.edu
1042655Sstever@eecs.umich.edusim_objects_fixed = False
1052655Sstever@eecs.umich.edusim_object_modfiles = set()
1062655Sstever@eecs.umich.edudef SimObject(source):
1072655Sstever@eecs.umich.edu    '''Add a SimObject python file as a python source object and add
1082655Sstever@eecs.umich.edu    it to a list of sim object modules'''
1092655Sstever@eecs.umich.edu
1102655Sstever@eecs.umich.edu    if sim_objects_fixed:
1112655Sstever@eecs.umich.edu        raise AttributeError, "Too late to call SimObject now."
1122655Sstever@eecs.umich.edu
1132655Sstever@eecs.umich.edu    if not isinstance(source, SCons.Node.FS.File):
1142655Sstever@eecs.umich.edu        source = File(source)
1152655Sstever@eecs.umich.edu
1162655Sstever@eecs.umich.edu    PySource('m5.objects', source)
1172655Sstever@eecs.umich.edu    modfile = basename(str(source))
1184007Ssaidi@eecs.umich.edu    assert modfile.endswith('.py')
1194007Ssaidi@eecs.umich.edu    modname = modfile[:-3]
1204007Ssaidi@eecs.umich.edu    sim_object_modfiles.add(modname)
1214007Ssaidi@eecs.umich.edu
1222655Sstever@eecs.umich.eduswig_sources = []
1232655Sstever@eecs.umich.edudef SwigSource(package, source):
1242655Sstever@eecs.umich.edu    '''Add a swig file to build'''
1252655Sstever@eecs.umich.edu    if not isinstance(source, SCons.Node.FS.File):
1262655Sstever@eecs.umich.edu        source = File(source)
127955SN/A    val = source,package
1283918Ssaidi@eecs.umich.edu    swig_sources.append(val)
1293918Ssaidi@eecs.umich.edu
1303918Ssaidi@eecs.umich.edu# Children should have access
1313918Ssaidi@eecs.umich.eduExport('Source')
1323918Ssaidi@eecs.umich.eduExport('PySource')
1333918Ssaidi@eecs.umich.eduExport('SimObject')
1343918Ssaidi@eecs.umich.eduExport('SwigSource')
1353918Ssaidi@eecs.umich.edu
1363918Ssaidi@eecs.umich.edu########################################################################
1373918Ssaidi@eecs.umich.edu#
1383918Ssaidi@eecs.umich.edu# Trace Flags
1393918Ssaidi@eecs.umich.edu#
1403918Ssaidi@eecs.umich.eduall_flags = {}
1413918Ssaidi@eecs.umich.edutrace_flags = []
1423940Ssaidi@eecs.umich.edudef TraceFlag(name, desc=''):
1433940Ssaidi@eecs.umich.edu    if name in all_flags:
1443940Ssaidi@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
1453942Ssaidi@eecs.umich.edu    flag = (name, (), desc)
1463940Ssaidi@eecs.umich.edu    trace_flags.append(flag)
1473515Ssaidi@eecs.umich.edu    all_flags[name] = ()
1483918Ssaidi@eecs.umich.edu
1493918Ssaidi@eecs.umich.edudef CompoundFlag(name, flags, desc=''):
1503515Ssaidi@eecs.umich.edu    if name in all_flags:
1512655Sstever@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
1523918Ssaidi@eecs.umich.edu
1533619Sbinkertn@umich.edu    compound = tuple(flags)
154955SN/A    for flag in compound:
155955SN/A        if flag not in all_flags:
1562655Sstever@eecs.umich.edu            raise AttributeError, "Trace flag %s not found" % flag
1573918Ssaidi@eecs.umich.edu        if all_flags[flag]:
1583619Sbinkertn@umich.edu            raise AttributeError, \
159955SN/A                "Compound flag can't point to another compound flag"
160955SN/A
1612655Sstever@eecs.umich.edu    flag = (name, compound, desc)
1623918Ssaidi@eecs.umich.edu    trace_flags.append(flag)
1633619Sbinkertn@umich.edu    all_flags[name] = compound
164955SN/A
165955SN/AExport('TraceFlag')
1662655Sstever@eecs.umich.eduExport('CompoundFlag')
1673918Ssaidi@eecs.umich.edu
1683683Sstever@eecs.umich.edu########################################################################
1692655Sstever@eecs.umich.edu#
1701869SN/A# Set some compiler variables
1711869SN/A#
172
173# Include file paths are rooted in this directory.  SCons will
174# automatically expand '.' to refer to both the source directory and
175# the corresponding build directory to pick up generated include
176# files.
177env.Append(CPPPATH=Dir('.'))
178
179# Add a flag defining what THE_ISA should be for all compilation
180env.Append(CPPDEFINES=[('THE_ISA','%s_ISA' % env['TARGET_ISA'].upper())])
181
182########################################################################
183#
184# Walk the tree and execute all SConscripts
185#
186srcdir = env['SRCDIR']
187for root, dirs, files in os.walk(srcdir, topdown=True):
188    if root == srcdir:
189        # we don't want to recurse back into this SConscript
190        continue
191
192    if 'SConscript' in files:
193        # strip off the srcdir part since scons will try to find the
194        # script in the build directory
195        base = root[len(srcdir) + 1:]
196        SConscript(joinpath(base, 'SConscript'))
197
198extra_string = env['EXTRAS']
199if extra_string and extra_string != '' and not extra_string.isspace():
200    for extra in extra_string.split(':'):
201        print 'Adding', extra, 'to source directory list'
202        env.Append(CPPPATH=[Dir(extra)])
203        for root, dirs, files in os.walk(extra, topdown=True):
204            if 'SConscript' in files:
205                subdir = root[len(os.path.dirname(extra))+1:]
206                print '  Found SConscript in', subdir
207                build_dir = joinpath(env['BUILDDIR'], subdir)
208                SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
209
210for opt in env.ExportOptions:
211    env.ConfigFile(opt)
212
213########################################################################
214#
215# Prevent any SimObjects from being added after this point, they
216# should all have been added in the SConscripts above
217#
218sim_objects_fixed = True
219
220########################################################################
221#
222# Manually turn python/generate.py into a python module and import it
223#
224generate_file = File('python/generate.py')
225generate_module = imp.new_module('generate')
226sys.modules['generate'] = generate_module
227exec file(generate_file.srcnode().abspath, 'r') in generate_module.__dict__
228
229########################################################################
230#
231# build a generate
232#
233from generate import Generate
234optionDict = dict([(opt, env[opt]) for opt in env.ExportOptions])
235generate = Generate(py_sources, sim_object_modfiles, optionDict)
236m5 = generate.m5
237
238########################################################################
239#
240# calculate extra dependencies
241#
242module_depends = ["m5", "m5.SimObject", "m5.params"]
243module_depends = [ File(generate.py_modules[dep]) for dep in module_depends ]
244file_depends = [ generate_file ]
245depends = module_depends + file_depends
246
247########################################################################
248#
249# Commands for the basic automatically generated python files
250#
251
252# Generate a file with all of the compile options in it
253env.Command('python/m5/defines.py', Value(optionDict),
254            generate.makeDefinesPyFile)
255PySource('m5', 'python/m5/defines.py')
256
257# Generate a file that wraps the basic top level files
258env.Command('python/m5/info.py',
259            [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
260            generate.makeInfoPyFile)
261PySource('m5', 'python/m5/info.py')
262
263# Generate an __init__.py file for the objects package
264env.Command('python/m5/objects/__init__.py',
265            [ Value(o) for o in sort_list(sim_object_modfiles) ],
266            generate.makeObjectsInitFile)
267PySource('m5.objects', 'python/m5/objects/__init__.py')
268
269########################################################################
270#
271# Create all of the SimObject param headers and enum headers
272#
273
274# Generate all of the SimObject param struct header files
275params_hh_files = []
276for name,simobj in generate.sim_objects.iteritems():
277    extra_deps = [ File(generate.py_modules[simobj.__module__]) ]
278
279    hh_file = File('params/%s.hh' % name)
280    params_hh_files.append(hh_file)
281    env.Command(hh_file, Value(name), generate.createSimObjectParam)
282    env.Depends(hh_file, depends + extra_deps)
283
284# Generate any parameter header files needed
285for name,param in generate.params.iteritems():
286    if isinstance(param, m5.params.VectorParamDesc):
287        ext = 'vptype'
288    else:
289        ext = 'ptype'
290
291    i_file = File('params/%s_%s.i' % (name, ext))
292    env.Command(i_file, Value(name), generate.createSwigParam)
293    env.Depends(i_file, depends)
294
295# Generate all enum header files
296for name,enum in generate.enums.iteritems():
297    extra_deps = [ File(generate.py_modules[enum.__module__]) ]
298
299    cc_file = File('enums/%s.cc' % name)
300    env.Command(cc_file, Value(name), generate.createEnumStrings)
301    env.Depends(cc_file, depends + extra_deps)
302    Source(cc_file)
303
304    hh_file = File('enums/%s.hh' % name)
305    env.Command(hh_file, Value(name), generate.createEnumParam)
306    env.Depends(hh_file, depends + extra_deps)
307
308# Build the big monolithic swigged params module (wraps all SimObject
309# param structs and enum structs)
310params_file = File('params/params.i')
311names = sort_list(generate.sim_objects.keys())
312env.Command(params_file, [ Value(v) for v in names ],
313            generate.buildParams)
314env.Depends(params_file, params_hh_files + depends)
315SwigSource('m5.objects', params_file)
316
317# Build all swig modules
318swig_modules = []
319for source,package in swig_sources:
320    filename = str(source)
321    assert filename.endswith('.i')
322
323    base = '.'.join(filename.split('.')[:-1])
324    module = basename(base)
325    cc_file = base + '_wrap.cc'
326    py_file = base + '.py'
327
328    env.Command([cc_file, py_file], source,
329                '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
330                '-o ${TARGETS[0]} $SOURCES')
331    env.Depends(py_file, source)
332    env.Depends(cc_file, source)
333
334    swig_modules.append(Value(module))
335    Source(cc_file)
336    PySource(package, py_file)
337
338# Generate the main swig init file
339env.Command('swig/init.cc', swig_modules, generate.makeSwigInit)
340Source('swig/init.cc')
341
342# Generate traceflags.py
343flags = [ Value(f) for f in trace_flags ]
344env.Command('base/traceflags.py', flags, generate.traceFlagsPy)
345PySource('m5', 'base/traceflags.py')
346
347env.Command('base/traceflags.hh', flags, generate.traceFlagsHH)
348env.Command('base/traceflags.cc', flags, generate.traceFlagsCC)
349Source('base/traceflags.cc')
350
351# Build the zip file
352py_compiled = []
353py_zip_depends = []
354for source in py_sources:
355    env.Command(source.compiled, source.source, generate.compilePyFile)
356    py_compiled.append(source.compiled)
357
358    # make the zipfile depend on the archive name so that the archive
359    # is rebuilt if the name changes
360    py_zip_depends.append(Value(source.arcname))
361
362# Add the zip file target to the environment.
363m5zip = File('m5py.zip')
364env.Command(m5zip, py_compiled, generate.buildPyZip)
365env.Depends(m5zip, py_zip_depends)
366
367########################################################################
368#
369# Define binaries.  Each different build type (debug, opt, etc.) gets
370# a slightly different build environment.
371#
372
373# List of constructed environments to pass back to SConstruct
374envList = []
375
376# This function adds the specified sources to the given build
377# environment, and returns a list of all the corresponding SCons
378# Object nodes (including an extra one for date.cc).  We explicitly
379# add the Object nodes so we can set up special dependencies for
380# date.cc.
381def make_objs(sources, env):
382    objs = [env.Object(s) for s in sources]
383    # make date.cc depend on all other objects so it always gets
384    # recompiled whenever anything else does
385    date_obj = env.Object('base/date.cc')
386    env.Depends(date_obj, objs)
387    objs.append(date_obj)
388    return objs
389
390# Function to create a new build environment as clone of current
391# environment 'env' with modified object suffix and optional stripped
392# binary.  Additional keyword arguments are appended to corresponding
393# build environment vars.
394def makeEnv(label, objsfx, strip = False, **kwargs):
395    newEnv = env.Copy(OBJSUFFIX=objsfx)
396    newEnv.Label = label
397    newEnv.Append(**kwargs)
398    exe = 'm5.' + label  # final executable
399    bin = exe + '.bin'   # executable w/o appended Python zip archive
400    newEnv.Program(bin, make_objs(cc_sources, newEnv))
401    if strip:
402        stripped_bin = bin + '.stripped'
403        if sys.platform == 'sunos5':
404            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
405        else:
406            cmd = 'strip $SOURCE -o $TARGET'
407        newEnv.Command(stripped_bin, bin, cmd)
408        bin = stripped_bin
409    targets = newEnv.Concat(exe, [bin, 'm5py.zip'])
410    newEnv.M5Binary = targets[0]
411    envList.append(newEnv)
412
413# Debug binary
414ccflags = {}
415if env['GCC']:
416    if sys.platform == 'sunos5':
417        ccflags['debug'] = '-gstabs+'
418    else:
419        ccflags['debug'] = '-ggdb3'
420    ccflags['opt'] = '-g -O3'
421    ccflags['fast'] = '-O3'
422    ccflags['prof'] = '-O3 -g -pg'
423elif env['SUNCC']:
424    ccflags['debug'] = '-g0'
425    ccflags['opt'] = '-g -O'
426    ccflags['fast'] = '-fast'
427    ccflags['prof'] = '-fast -g -pg'
428elif env['ICC']:
429    ccflags['debug'] = '-g -O0'
430    ccflags['opt'] = '-g -O'
431    ccflags['fast'] = '-fast'
432    ccflags['prof'] = '-fast -g -pg'
433else:
434    print 'Unknown compiler, please fix compiler options'
435    Exit(1)
436
437makeEnv('debug', '.do',
438        CCFLAGS = Split(ccflags['debug']),
439        CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
440
441# Optimized binary
442makeEnv('opt', '.o',
443        CCFLAGS = Split(ccflags['opt']),
444        CPPDEFINES = ['TRACING_ON=1'])
445
446# "Fast" binary
447makeEnv('fast', '.fo', strip = True,
448        CCFLAGS = Split(ccflags['fast']),
449        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
450
451# Profiled binary
452makeEnv('prof', '.po',
453        CCFLAGS = Split(ccflags['prof']),
454        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
455        LINKFLAGS = '-pg')
456
457Return('envList')
458