104
|
1 #!/usr/bin/python
|
|
2
|
213
|
3 import sys, argparse
|
205
|
4 import c3, ppci, codegen
|
|
5 import codegenarm
|
253
|
6 from optimize import optimize
|
205
|
7 import outstream
|
246
|
8 import hexfile
|
253
|
9 import logging
|
|
10
|
|
11 def logLevel(s):
|
|
12 numeric_level = getattr(logging, s.upper(), None)
|
|
13 if not isinstance(numeric_level, int):
|
|
14 raise ValueError('Invalid log level: {}'.format(s))
|
|
15 return numeric_level
|
105
|
16
|
205
|
17 # Parse arguments:
|
204
|
18 parser = argparse.ArgumentParser(description='lcfos Compiler')
|
213
|
19 parser.add_argument('source', type=argparse.FileType('r'), \
|
|
20 help='the source file to build')
|
253
|
21 parser.add_argument('--dumpir', action='store_true', help="Dump IR-code")
|
255
|
22 parser.add_argument('--dumpasm', action='store_true', help="Dump ASM-code")
|
|
23 parser.add_argument('--optimize', action='store_true', help="Optimize")
|
205
|
24 parser.add_argument('-o', '--output', help='Output file', metavar='filename')
|
246
|
25 parser.add_argument('--hexfile', help='Output hexfile', type=argparse.FileType('w'))
|
253
|
26 parser.add_argument('--log', help='Log level (INFO,DEBUG)', type=logLevel)
|
104
|
27
|
255
|
28 def zcc(src, outs, diag, dumpir=False, do_optimize=False):
|
|
29 logging.info('Zcc started')
|
207
|
30 # Front end:
|
|
31 c3b = c3.Builder(diag)
|
|
32 ircode = c3b.build(src)
|
|
33 if not ircode:
|
249
|
34 return
|
104
|
35
|
219
|
36 # Optimization passes:
|
255
|
37 if do_optimize:
|
|
38 optimize(ircode)
|
219
|
39
|
249
|
40 if dumpir:
|
207
|
41 ircode.dump()
|
249
|
42
|
207
|
43 # Code generation:
|
|
44 cg = codegenarm.ArmCodeGenerator(outs)
|
|
45 obj = cg.generate(ircode)
|
249
|
46 return True
|
|
47
|
258
|
48 logformat='%(asctime)s|%(levelname)s|%(name)s|%(message)s'
|
|
49
|
249
|
50 def main(args):
|
258
|
51 logging.basicConfig(format=logformat, level=args.log)
|
249
|
52 src = args.source.read()
|
|
53 args.source.close()
|
|
54 diag = ppci.DiagnosticsManager()
|
|
55 outs = outstream.TextOutputStream()
|
|
56
|
|
57 # Invoke compiler:
|
255
|
58 res = zcc(src, outs, diag, dumpir=args.dumpir, do_optimize=args.optimize)
|
249
|
59 if not res:
|
|
60 diag.printErrors(src)
|
|
61 sys.exit(1)
|
205
|
62
|
255
|
63 if args.dumpasm:
|
|
64 outs.dump()
|
105
|
65
|
237
|
66 code_bytes = outs.sections['code'].to_bytes()
|
238
|
67 #print('bytes:', code_bytes)
|
207
|
68 if args.output:
|
|
69 output_filename = args.output
|
|
70 else:
|
237
|
71 output_filename = 'b.output'
|
249
|
72
|
237
|
73 with open(output_filename, 'wb') as f:
|
|
74 f.write(code_bytes)
|
104
|
75
|
246
|
76 if args.hexfile:
|
255
|
77 logging.info('Creating hexfile')
|
246
|
78 hf = hexfile.HexFile()
|
|
79 hf.addRegion(0x08000000, code_bytes)
|
|
80 hf.save(args.hexfile)
|
|
81
|
207
|
82 if __name__ == '__main__':
|
213
|
83 arguments = parser.parse_args()
|
|
84 main(arguments)
|
205
|
85
|