292
|
1 #!/usr/bin/env python
|
104
|
2
|
287
|
3 import sys
|
|
4 import argparse
|
|
5 import logging
|
|
6
|
313
|
7 from ppci.c3 import Builder, AstPrinter
|
287
|
8 import ppci
|
312
|
9 from ppci.irutils import Verifier, Writer
|
301
|
10 from ppci.codegen import CodeGenerator
|
205
|
11 import outstream
|
292
|
12 from utils import HexFile
|
290
|
13 import target
|
311
|
14 from ppci import irutils
|
|
15 import io
|
253
|
16
|
289
|
17
|
281
|
18 logformat='%(asctime)s|%(levelname)s|%(name)s|%(message)s'
|
|
19
|
289
|
20
|
253
|
21 def logLevel(s):
|
312
|
22 """ Converts a string to a valid logging level """
|
253
|
23 numeric_level = getattr(logging, s.upper(), None)
|
|
24 if not isinstance(numeric_level, int):
|
|
25 raise ValueError('Invalid log level: {}'.format(s))
|
|
26 return numeric_level
|
105
|
27
|
289
|
28
|
312
|
29 class RstFormatter(logging.Formatter):
|
|
30 """ Formatter that tries to create an rst document """
|
|
31 def __init__(self):
|
|
32 super().__init__(fmt=logformat)
|
|
33
|
|
34 def format(self, record):
|
|
35 s = super().format(record)
|
314
|
36 s += '\n'
|
313
|
37 if hasattr(record, 'c3_ast'):
|
|
38 f = io.StringIO()
|
|
39 print('', file=f)
|
|
40 print('', file=f)
|
|
41 print('.. code::', file=f)
|
|
42 print('', file=f)
|
|
43 AstPrinter().printAst(record.c3_ast, f)
|
|
44 #Writer(' ').write(record.c3_ast, f)
|
|
45 print('', file=f)
|
|
46 s += '\n' + f.getvalue()
|
312
|
47 if hasattr(record, 'ircode'):
|
|
48 f = io.StringIO()
|
|
49 print('', file=f)
|
|
50 print('', file=f)
|
|
51 print('.. code::', file=f)
|
|
52 print('', file=f)
|
|
53 Writer(' ').write(record.ircode, f)
|
|
54 print('', file=f)
|
|
55 s += '\n' + f.getvalue()
|
|
56 if hasattr(record, 'irfunc'):
|
|
57 f = io.StringIO()
|
|
58 print('', file=f)
|
|
59 print('', file=f)
|
|
60 print('.. code::', file=f)
|
|
61 print('', file=f)
|
|
62 Writer(' ').write_function(record.irfunc, f)
|
|
63 print('', file=f)
|
|
64 s += '\n' + f.getvalue()
|
|
65 if hasattr(record, 'ppci_frame'):
|
|
66 f = io.StringIO()
|
|
67 frame = record.ppci_frame
|
|
68 print('', file=f)
|
|
69 print('.. code::', file=f)
|
|
70 print('', file=f)
|
|
71 print(' {}'.format(frame.name), file=f)
|
|
72 for i in frame.instructions:
|
|
73 print(' {}'.format(i),file=f)
|
|
74 print('', file=f)
|
|
75 s += '\n' + f.getvalue()
|
|
76 if hasattr(record, 'ra_cfg'):
|
|
77 f = io.StringIO()
|
|
78 print('', file=f)
|
|
79 print('', file=f)
|
|
80 print('.. graphviz::', file=f)
|
|
81 print('', file=f)
|
|
82 print(' digraph G {', file=f)
|
|
83 cfg = record.ra_cfg
|
|
84 cfg.to_dot(f)
|
|
85 print(' }', file=f)
|
|
86 print('', file=f)
|
|
87 s += '\n' + f.getvalue()
|
314
|
88 if hasattr(record, 'ra_ig'):
|
|
89 f = io.StringIO()
|
|
90 print('', file=f)
|
|
91 print('', file=f)
|
|
92 print('.. graphviz::', file=f)
|
|
93 print('', file=f)
|
|
94 print(' digraph G {', file=f)
|
|
95 ig = record.ra_ig
|
|
96 ig.to_dot(f)
|
|
97 print(' }', file=f)
|
|
98 print('', file=f)
|
|
99 s += '\n' + f.getvalue()
|
312
|
100 return s
|
|
101
|
|
102
|
290
|
103 target_list = [target.armtarget]
|
292
|
104 targets = {t.name: t for t in target_list}
|
|
105 targetnames = list(targets.keys())
|
290
|
106
|
205
|
107 # Parse arguments:
|
204
|
108 parser = argparse.ArgumentParser(description='lcfos Compiler')
|
287
|
109 # Input:
|
213
|
110 parser.add_argument('source', type=argparse.FileType('r'), \
|
287
|
111 help='the source file to build', nargs="+")
|
290
|
112 parser.add_argument('-i', '--imp', type=argparse.FileType('r'), \
|
296
|
113 help='Possible import module', action='append', default=[])
|
287
|
114
|
253
|
115 parser.add_argument('--dumpir', action='store_true', help="Dump IR-code")
|
255
|
116 parser.add_argument('--optimize', action='store_true', help="Optimize")
|
290
|
117 parser.add_argument('--target', help="Backend selection",
|
292
|
118 choices=targetnames, required=True)
|
205
|
119 parser.add_argument('-o', '--output', help='Output file', metavar='filename')
|
290
|
120 parser.add_argument('--hexfile', help='Output hexfile',
|
|
121 type=argparse.FileType('w'))
|
253
|
122 parser.add_argument('--log', help='Log level (INFO,DEBUG)', type=logLevel)
|
104
|
123
|
288
|
124
|
292
|
125 def zcc(srcs, imps, tg, outs, diag, dumpir=False):
|
287
|
126 """
|
|
127 Compile sources into output stream.
|
|
128 Sources is an iterable of open files.
|
|
129 """
|
255
|
130 logging.info('Zcc started')
|
207
|
131 # Front end:
|
301
|
132 c3b = Builder(diag, tg)
|
|
133 cg = CodeGenerator(tg)
|
292
|
134
|
|
135 # TODO: remove this arm specifics:
|
|
136 outs.getSection('code').address = 0x08000000
|
|
137 outs.getSection('data').address = 0x20000000
|
|
138
|
|
139 # Emit some custom start code:
|
|
140 tg.startCode(outs)
|
287
|
141 for ircode in c3b.build(srcs, imps):
|
|
142 if not ircode:
|
|
143 return
|
313
|
144
|
|
145 d = {'ircode':ircode}
|
|
146 logging.info('Verifying code {}'.format(ircode), extra=d)
|
290
|
147 # Optimization passes, TODO
|
312
|
148 Verifier().verify(ircode)
|
289
|
149
|
287
|
150 # Code generation:
|
312
|
151 d = {'ircode':ircode}
|
|
152 logging.info('Starting code generation for {}'.format(ircode), extra=d)
|
292
|
153 cg.generate(ircode, outs)
|
|
154 # TODO: fixup references, do this in another way?
|
|
155 outs.backpatch()
|
|
156 outs.backpatch() # Why two times?
|
288
|
157 return c3b.ok
|
|
158
|
249
|
159
|
|
160 def main(args):
|
313
|
161 #logging.getLogger().setLevel(logging.DEBUG)
|
312
|
162 #logging.getLogger().addHandler(RstLogHandler())
|
313
|
163 #fh = logging.FileHandler('log.rst', mode='w')
|
|
164 #fh.setFormatter(RstFormatter())
|
|
165 #logging.getLogger().addHandler(fh)
|
312
|
166
|
292
|
167 tg = targets[args.target]
|
249
|
168 diag = ppci.DiagnosticsManager()
|
|
169 outs = outstream.TextOutputStream()
|
|
170
|
296
|
171 res = zcc(args.source, args.imp, tg, outs, diag, dumpir=args.dumpir)
|
249
|
172 if not res:
|
293
|
173 diag.printErrors()
|
276
|
174 return 1
|
205
|
175
|
313
|
176 logging.info('Assembly created', extra={'zcc_outs':outs})
|
105
|
177
|
237
|
178 code_bytes = outs.sections['code'].to_bytes()
|
207
|
179 if args.output:
|
|
180 output_filename = args.output
|
287
|
181 with open(output_filename, 'wb') as f:
|
|
182 f.write(code_bytes)
|
104
|
183
|
246
|
184 if args.hexfile:
|
255
|
185 logging.info('Creating hexfile')
|
292
|
186 hf = HexFile()
|
246
|
187 hf.addRegion(0x08000000, code_bytes)
|
|
188 hf.save(args.hexfile)
|
276
|
189 return 0
|
246
|
190
|
288
|
191
|
207
|
192 if __name__ == '__main__':
|
213
|
193 arguments = parser.parse_args()
|
276
|
194 sys.exit(main(arguments))
|