view python/zcc.py @ 251:6ed3d3a82a63

Added another c3 example. First import attempt
author Windel Bouwman
date Mon, 29 Jul 2013 20:23:13 +0200
parents e41e4109addd
children c4370696ccc7
line wrap: on
line source

#!/usr/bin/python

import sys, argparse
import c3, ppci, codegen
import codegenarm
from transform import CleanPass, SameImmLoadDeletePass
import outstream
import hexfile

# Parse arguments:
parser = argparse.ArgumentParser(description='lcfos Compiler')
parser.add_argument('source', type=argparse.FileType('r'), \
  help='the source file to build')
parser.add_argument('-d', '--dumpir', action='store_true', help="Dump IR-code")
parser.add_argument('-o', '--output', help='Output file', metavar='filename')
parser.add_argument('--hexfile', help='Output hexfile', type=argparse.FileType('w'))

def zcc(src, outs, diag, dumpir=False):
    # Front end:
    c3b = c3.Builder(diag)
    ircode = c3b.build(src)
    if not ircode:
        return

    # Optimization passes:
    ircode.check()
    cp = CleanPass()
    cp.run(ircode)
    ircode.check()
    sidp = SameImmLoadDeletePass()
    sidp.run(ircode)
    ircode.check()

    if dumpir:
        ircode.dump()

    # Code generation:
    cg = codegenarm.ArmCodeGenerator(outs)
    obj = cg.generate(ircode)
    return True

def main(args):
    src = args.source.read()
    args.source.close()
    diag = ppci.DiagnosticsManager()
    outs = outstream.TextOutputStream()

    # Invoke compiler:
    res = zcc(src, outs, diag, dumpir=args.dumpir)
    if not res:
        diag.printErrors(src)
        sys.exit(1)

    if args.dumpir:
        outs.dump()

    code_bytes = outs.sections['code'].to_bytes()
    #print('bytes:', code_bytes)
    if args.output:
        output_filename = args.output
    else:
        output_filename = 'b.output'

    with open(output_filename, 'wb') as f:
        f.write(code_bytes)

    if args.hexfile:
        hf = hexfile.HexFile()
        hf.addRegion(0x08000000, code_bytes)
        hf.save(args.hexfile)

if __name__ == '__main__':
    arguments = parser.parse_args()
    main(arguments)