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")
|
205
|
22 parser.add_argument('-o', '--output', help='Output file', metavar='filename')
|
246
|
23 parser.add_argument('--hexfile', help='Output hexfile', type=argparse.FileType('w'))
|
253
|
24 parser.add_argument('--log', help='Log level (INFO,DEBUG)', type=logLevel)
|
104
|
25
|
249
|
26 def zcc(src, outs, diag, dumpir=False):
|
207
|
27 # Front end:
|
|
28 c3b = c3.Builder(diag)
|
|
29 ircode = c3b.build(src)
|
253
|
30 logging.info('Intermediate code generated')
|
207
|
31 if not ircode:
|
249
|
32 return
|
104
|
33
|
219
|
34 # Optimization passes:
|
253
|
35 optimize(ircode)
|
|
36 logging.info('IR-code optimized')
|
219
|
37
|
249
|
38 if dumpir:
|
207
|
39 ircode.dump()
|
249
|
40
|
207
|
41 # Code generation:
|
|
42 cg = codegenarm.ArmCodeGenerator(outs)
|
|
43 obj = cg.generate(ircode)
|
249
|
44 return True
|
|
45
|
|
46 def main(args):
|
253
|
47 logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=args.log)
|
249
|
48 src = args.source.read()
|
|
49 args.source.close()
|
253
|
50 logging.info('Source loaded')
|
249
|
51 diag = ppci.DiagnosticsManager()
|
|
52 outs = outstream.TextOutputStream()
|
|
53
|
|
54 # Invoke compiler:
|
|
55 res = zcc(src, outs, diag, dumpir=args.dumpir)
|
|
56 if not res:
|
|
57 diag.printErrors(src)
|
|
58 sys.exit(1)
|
205
|
59
|
253
|
60 #if args.dumpir:
|
|
61 # outs.dump()
|
105
|
62
|
237
|
63 code_bytes = outs.sections['code'].to_bytes()
|
238
|
64 #print('bytes:', code_bytes)
|
207
|
65 if args.output:
|
|
66 output_filename = args.output
|
|
67 else:
|
237
|
68 output_filename = 'b.output'
|
249
|
69
|
237
|
70 with open(output_filename, 'wb') as f:
|
|
71 f.write(code_bytes)
|
104
|
72
|
246
|
73 if args.hexfile:
|
|
74 hf = hexfile.HexFile()
|
|
75 hf.addRegion(0x08000000, code_bytes)
|
|
76 hf.save(args.hexfile)
|
253
|
77 logging.info('Hexfile created')
|
246
|
78
|
207
|
79 if __name__ == '__main__':
|
213
|
80 arguments = parser.parse_args()
|
|
81 main(arguments)
|
205
|
82
|