Debian Codegraph @

rpython/translator/driver.py

raw symbols SCIP
1 import sys, os
2 import os.path
3 import shutil
4
5 from rpython.translator.translator import TranslationContext
6 from rpython.translator.tool.taskengine import SimpleTaskEngine
7 from rpython.translator.goal import query
8 from rpython.translator.timing import Timer
9 from rpython.annotator.listdef import s_list_of_strings
10 from rpython.annotator import policy as annpolicy
11 from rpython.tool.udir import udir
12 from rpython.rlib.debug import debug_start, debug_print, debug_stop
13 from rpython.rlib.entrypoint import secondary_entrypoints,\
14 annotated_jit_entrypoints
15
16 import py
17 from rpython.tool.ansi_print import AnsiLogger
18
19 log = AnsiLogger("translation")
20
21
22 def taskdef(deps, title, new_state=None, expected_states=[],
23 idemp=False, earlycheck=None):
24 def decorator(taskfunc):
25 taskfunc.task_deps = deps
26 taskfunc.task_title = title
27 taskfunc.task_newstate = None
28 taskfunc.task_expected_states = expected_states
29 taskfunc.task_idempotent = idemp
30 taskfunc.task_earlycheck = earlycheck
31 return taskfunc
32 return decorator
33
34 # TODO:
35 # sanity-checks using states
36
37 # set of translation steps to profile
38 PROFILE = set([])
39
40 class Instrument(Exception):
41 pass
42
43
44 class ProfInstrument(object):
45 name = "profinstrument"
46 def __init__(self, datafile, compiler):
47 self.datafile = datafile
48 self.compiler = compiler
49
50 def first(self):
51 return self.compiler._build()
52
53 def probe(self, exe, args):
54 env = os.environ.copy()
55 env['PYPY_INSTRUMENT_COUNTERS'] = str(self.datafile)
56 self.compiler.platform.execute(exe, args, env=env)
57
58 def after(self):
59 # xxx
60 os._exit(0)
61
62
63 class TranslationDriver(SimpleTaskEngine):
64 _backend_extra_options = {}
65
66 def __init__(self, setopts=None, default_goal=None,
67 disable=[],
68 exe_name=None, extmod_name=None,
69 config=None, overrides=None):
70 from rpython.config import translationoption
71 self.timer = Timer()
72 SimpleTaskEngine.__init__(self)
73
74 self.log = log
75
76 if config is None:
77 config = translationoption.get_combined_translation_config(translating=True)
78 # XXX patch global variable with translation config
79 translationoption._GLOBAL_TRANSLATIONCONFIG = config
80 self.config = config
81 if overrides is not None:
82 self.config.override(overrides)
83
84 if setopts is not None:
85 self.config.set(**setopts)
86
87 self.exe_name = exe_name
88 self.extmod_name = extmod_name
89
90 self.done = {}
91
92 self.disable(disable)
93
94 if default_goal:
95 default_goal, = self.backend_select_goals([default_goal])
96 if default_goal in self._maybe_skip():
97 default_goal = None
98
99 self.default_goal = default_goal
100 self.extra_goals = []
101 self.exposed = []
102
103 # expose tasks
104 def expose_task(task, backend_goal=None):
105 if backend_goal is None:
106 backend_goal = task
107 def proc():
108 return self.proceed(backend_goal)
109 self.exposed.append(task)
110 setattr(self, task, proc)
111
112 backend, ts = self.get_backend_and_type_system()
113 for task in self.tasks:
114 explicit_task = task
115 if task == 'annotate':
116 expose_task(task)
117 else:
118 task, postfix = task.split('_')
119 if task in ('rtype', 'backendopt', 'llinterpret',
120 'pyjitpl'):
121 if ts:
122 if ts == postfix:
123 expose_task(task, explicit_task)
124 else:
125 expose_task(explicit_task)
126 elif task in ('source', 'compile', 'run'):
127 if backend:
128 if backend == postfix:
129 expose_task(task, explicit_task)
130 elif ts:
131 if ts == 'lltype':
132 expose_task(explicit_task)
133 else:
134 expose_task(explicit_task)
135
136 def set_extra_goals(self, goals):
137 self.extra_goals = goals
138
139 def set_backend_extra_options(self, extra_options):
140 self._backend_extra_options = extra_options
141
142 def get_info(self): # XXX more?
143 d = {'backend': self.config.translation.backend}
144 return d
145
146 def get_backend_and_type_system(self):
147 type_system = self.config.translation.type_system
148 backend = self.config.translation.backend
149 return backend, type_system
150
151 def backend_select_goals(self, goals):
152 backend, ts = self.get_backend_and_type_system()
153 postfixes = [''] + ['_'+p for p in (backend, ts) if p]
154 l = []
155 for goal in goals:
156 for postfix in postfixes:
157 cand = "%s%s" % (goal, postfix)
158 if cand in self.tasks:
159 new_goal = cand
160 break
161 else:
162 raise Exception("cannot infer complete goal from: %r" % goal)
163 l.append(new_goal)
164 return l
165
166 def disable(self, to_disable):
167 self._disabled = to_disable
168
169 def _maybe_skip(self):
170 maybe_skip = []
171 if self._disabled:
172 for goal in self.backend_select_goals(self._disabled):
173 maybe_skip.extend(self._depending_on_closure(goal))
174 return dict.fromkeys(maybe_skip).keys()
175
176 def setup(self, entry_point, inputtypes, policy=None, extra={}, empty_translator=None):
177 standalone = inputtypes is None
178 self.standalone = standalone
179
180 if standalone:
181 # the 'argv' parameter
182 inputtypes = [s_list_of_strings]
183 self.inputtypes = inputtypes
184
185 if policy is None:
186 policy = annpolicy.AnnotatorPolicy()
187 self.policy = policy
188
189 self.extra = extra
190
191 if empty_translator:
192 translator = empty_translator
193 else:
194 translator = TranslationContext(config=self.config)
195
196 self.entry_point = entry_point
197 self.translator = translator
198 self.libdef = None
199 self.secondary_entrypoints = []
200
201 if self.config.translation.secondaryentrypoints:
202 for key in self.config.translation.secondaryentrypoints.split(","):
203 try:
204 points = secondary_entrypoints[key]
205 except KeyError:
206 raise KeyError("Entrypoint %r not found (not in %r)" %
207 (key, secondary_entrypoints.keys()))
208 self.secondary_entrypoints.extend(points)
209
210 self.translator.driver_instrument_result = self.instrument_result
211
212 def setup_library(self, libdef, policy=None, extra={}, empty_translator=None):
213 """ Used by carbon python only. """
214 self.setup(None, None, policy, extra, empty_translator)
215 self.libdef = libdef
216 self.secondary_entrypoints = libdef.functions
217
218 def instrument_result(self, args):
219 backend, ts = self.get_backend_and_type_system()
220 if backend != 'c' or sys.platform == 'win32':
221 raise Exception("instrumentation requires the c backend"
222 " and unix for now")
223
224 datafile = udir.join('_instrument_counters')
225 makeProfInstrument = lambda compiler: ProfInstrument(datafile, compiler)
226
227 pid = os.fork()
228 if pid == 0:
229 # child compiling and running with instrumentation
230 self.config.translation.instrument = True
231 self.config.translation.instrumentctl = (makeProfInstrument,
232 args)
233 raise Instrument
234 else:
235 pid, status = os.waitpid(pid, 0)
236 if os.WIFEXITED(status):
237 status = os.WEXITSTATUS(status)
238 if status != 0:
239 raise Exception("instrumentation child failed: %d" % status)
240 else:
241 raise Exception("instrumentation child aborted")
242 import array, struct
243 n = datafile.size()//struct.calcsize('L')
244 datafile = datafile.open('rb')
245 counters = array.array('L')
246 counters.fromfile(datafile, n)
247 datafile.close()
248 return counters
249
250 def info(self, msg):
251 log.info(msg)
252
253 def _profile(self, goal, func):
254 from cProfile import Profile
255 from rpython.tool.lsprofcalltree import KCacheGrind
256 d = {'func':func}
257 prof = Profile()
258 prof.runctx("res = func()", globals(), d)
259 KCacheGrind(prof).output(open(goal + ".out", "w"))
260 return d['res']
261
262 def _do(self, goal, func, *args, **kwds):
263 title = func.task_title
264 if goal in self.done:
265 self.log.info("already done: %s" % title)
266 return
267 else:
268 self.log.info("%s..." % title)
269 debug_start('translation-task')
270 debug_print('starting', goal)
271 self.timer.start_event(goal)
272 try:
273 instrument = False
274 try:
275 if goal in PROFILE:
276 res = self._profile(goal, func)
277 else:
278 res = func()
279 except Instrument:
280 instrument = True
281 if not func.task_idempotent:
282 self.done[goal] = True
283 if instrument:
284 self.proceed('compile')
285 assert False, 'we should not get here'
286 finally:
287 try:
288 debug_stop('translation-task')
289 self.timer.end_event(goal)
290 except (KeyboardInterrupt, SystemExit):
291 raise
292 except:
293 pass
294 #import gc; gc.dump_rpy_heap('rpyheap-after-%s.dump' % goal)
295 return res
296
297 @taskdef([], "Annotating&simplifying")
298 def task_annotate(self):
299 """ Annotate
300 """
301 # includes annotation and annotatation simplifications
302 translator = self.translator
303 policy = self.policy
304 self.log.info('with policy: %s.%s' % (policy.__class__.__module__, policy.__class__.__name__))
305
306 annotator = translator.buildannotator(policy=policy)
307
308 if self.secondary_entrypoints is not None:
309 for func, inputtypes in self.secondary_entrypoints:
310 if inputtypes == Ellipsis:
311 continue
312 annotator.build_types(func, inputtypes, False)
313
314 if self.entry_point:
315 s = annotator.build_types(self.entry_point, self.inputtypes)
316 translator.entry_point_graph = annotator.bookkeeper.getdesc(self.entry_point).getuniquegraph()
317 else:
318 s = None
319
320 self.sanity_check_annotation()
321 if self.entry_point and self.standalone and s.knowntype != int:
322 raise Exception("stand-alone program entry point must return an "
323 "int (and not, e.g., None or always raise an "
324 "exception).")
325 annotator.complete()
326 annotator.simplify()
327 return s
328
329
330 def sanity_check_annotation(self):
331 translator = self.translator
332 irreg = query.qoutput(query.check_exceptblocks_qgen(translator))
333 if irreg:
334 self.log.info("Some exceptblocks seem insane")
335
336 lost = query.qoutput(query.check_methods_qgen(translator))
337 assert not lost, "lost methods, something gone wrong with the annotation of method defs"
338
339 RTYPE = 'rtype_lltype'
340 @taskdef(['annotate'], "RTyping")
341 def task_rtype_lltype(self):
342 """ RTyping - lltype version
343 """
344 rtyper = self.translator.buildrtyper()
345 rtyper.specialize(dont_simplify_again=True)
346
347 @taskdef([RTYPE], "JIT compiler generation")
348 def task_pyjitpl_lltype(self):
349 """ Generate bytecodes for JIT and flow the JIT helper functions
350 lltype version
351 """
352 from rpython.jit.codewriter.policy import JitPolicy
353 get_policy = self.extra.get('jitpolicy', None)
354 if get_policy is None:
355 self.jitpolicy = JitPolicy()
356 else:
357 self.jitpolicy = get_policy(self)
358 #
359 from rpython.jit.metainterp.warmspot import apply_jit
360 apply_jit(self.translator, policy=self.jitpolicy,
361 backend_name=self.config.translation.jit_backend, inline=True)
362 #
363 self.log.info("the JIT compiler was generated")
364
365 @taskdef([RTYPE], "test of the JIT on the llgraph backend")
366 def task_jittest_lltype(self):
367 """ Run with the JIT on top of the llgraph backend
368 """
369 # parent process loop: spawn a child, wait for the child to finish,
370 # print a message, and restart
371 from rpython.translator.goal import unixcheckpoint
372 unixcheckpoint.restartable_point(auto='run')
373 # load the module rpython/jit/tl/jittest.py, which you can hack at
374 # and restart without needing to restart the whole translation process
375 from rpython.jit.tl import jittest
376 jittest.jittest(self)
377
378 BACKENDOPT = 'backendopt_lltype'
379 @taskdef([RTYPE, '??pyjitpl_lltype', '??jittest_lltype'], "lltype back-end optimisations")
380 def task_backendopt_lltype(self):
381 """ Run all backend optimizations - lltype version
382 """
383 from rpython.translator.backendopt.all import backend_optimizations
384 backend_optimizations(self.translator, replace_we_are_jitted=True)
385
386
387 STACKCHECKINSERTION = 'stackcheckinsertion_lltype'
388 @taskdef(['?'+BACKENDOPT, RTYPE, 'annotate'], "inserting stack checks")
389 def task_stackcheckinsertion_lltype(self):
390 from rpython.translator.transform import insert_ll_stackcheck
391 count = insert_ll_stackcheck(self.translator)
392 self.log.info("inserted %d stack checks." % (count,))
393
394
395 def possibly_check_for_boehm(self):
396 if self.config.translation.gc == "boehm":
397 from rpython.rtyper.tool.rffi_platform import configure_boehm
398 from rpython.translator.platform import CompilationError
399 try:
400 configure_boehm(self.translator.platform)
401 except CompilationError as e:
402 i = 'Boehm GC not installed. Try e.g. "translate.py --gc=minimark"'
403 raise Exception(str(e) + '\n' + i)
404
405 @taskdef([STACKCHECKINSERTION, '?'+BACKENDOPT, RTYPE, '?annotate'],
406 "Creating database for generating c source",
407 earlycheck = possibly_check_for_boehm)
408 def task_database_c(self):
409 """ Create a database for further backend generation
410 """
411 translator = self.translator
412 if translator.annotator is not None:
413 translator.frozen = True
414
415 standalone = self.standalone
416 get_gchooks = self.extra.get('get_gchooks', lambda: None)
417 gchooks = get_gchooks()
418
419 if standalone:
420 from rpython.translator.c.genc import CStandaloneBuilder
421 cbuilder = CStandaloneBuilder(self.translator, self.entry_point,
422 config=self.config, gchooks=gchooks,
423 secondary_entrypoints=
424 self.secondary_entrypoints + annotated_jit_entrypoints)
425 else:
426 from rpython.translator.c.dlltool import CLibraryBuilder
427 functions = [(self.entry_point, None)] + self.secondary_entrypoints + annotated_jit_entrypoints
428 cbuilder = CLibraryBuilder(self.translator, self.entry_point,
429 functions=functions,
430 name='libtesting',
431 config=self.config,
432 gchooks=gchooks)
433 if not standalone: # xxx more messy
434 cbuilder.modulename = self.extmod_name
435 database = cbuilder.build_database()
436 self.log.info("database for generating C source was created")
437 self.cbuilder = cbuilder
438 self.database = database
439
440 @taskdef(['database_c'], "Generating c source")
441 def task_source_c(self):
442 """ Create C source files from the generated database
443 """
444 cbuilder = self.cbuilder
445 database = self.database
446 if self._backend_extra_options.get('c_debug_defines', False):
447 defines = cbuilder.DEBUG_DEFINES
448 else:
449 defines = {}
450 if self.exe_name is not None:
451 exe_name = self.exe_name % self.get_info()
452 else:
453 exe_name = None
454 c_source_filename = cbuilder.generate_source(database, defines,
455 exe_name=exe_name)
456 self.log.info("written: %s" % (c_source_filename,))
457 if self.config.translation.dump_static_data_info:
458 from rpython.translator.tool.staticsizereport import dump_static_data_info
459 targetdir = cbuilder.targetdir
460 fname = dump_static_data_info(self.log, database, targetdir)
461 dstname = self.compute_exe_name() + '.staticdata.info'
462 shutil_copy(str(fname), str(dstname))
463 self.log.info('Static data info written to %s' % dstname)
464
465 def compute_exe_name(self, suffix=''):
466 newexename = self.exe_name % self.get_info()
467 if '/' not in newexename and '\\' not in newexename:
468 newexename = './' + newexename
469 if suffix:
470 # Replace the last `.sfx` with the suffix
471 newname = py.path.local(newexename.rsplit('.', 1)[0])
472 newname = newname.new(basename=newname.basename + suffix)
473 return newname
474 return py.path.local(newexename)
475
476 def create_exe(self):
477 """ Copy the compiled executable into current directory, which is
478 pypy/goal on nightly builds
479 """
480 if self.exe_name is not None:
481 exename = self.c_entryp
482 newexename = py.path.local(exename.basename)
483 shutil_copy(str(exename), str(newexename))
484 self.log.info("copied: %s to %s" % (exename, newexename,))
485 if self.cbuilder.shared_library_name is not None:
486 soname = self.cbuilder.shared_library_name
487 newsoname = newexename.new(basename=soname.basename)
488 shutil_copy(str(soname), str(newsoname))
489 self.log.info("copied: %s to %s" % (soname, newsoname,))
490 if hasattr(self.cbuilder, 'executable_name_w'):
491 # Copy pypyw.exe
492 exename_w = self.cbuilder.executable_name_w
493 newexename_w = py.path.local(exename_w.basename)
494 self.log.info("copied: %s to %s" % (exename_w, newexename_w,))
495 shutil_copy(str(exename_w), str(newexename_w))
496 # for pypy, the import library is renamed and moved to
497 # libs/python32.lib, according to the pragma in pyconfig.h
498 libname = self.config.translation.libname
499 oldlibname = soname.new(ext='lib')
500 if not libname:
501 libname = oldlibname.basename
502 libname = str(newsoname.dirpath().join(libname))
503 shutil.copyfile(str(oldlibname), libname)
504 self.log.info("copied: %s to %s" % (oldlibname, libname,))
505 # the pdb file goes in the same place as pypy(w).exe
506 ext_to_copy = ['pdb',]
507 for ext in ext_to_copy:
508 name = soname.new(ext=ext)
509 newname = newexename.new(basename=soname.basename)
510 shutil.copyfile(str(name), str(newname.new(ext=ext)))
511 self.log.info("copied: %s" % (newname,))
512 # HACK: copy libcffi-*.dll which is required for venvs
513 # At some point, we should stop doing this, and instead
514 # use the artifact from packaging the build instead
515 libffi = py.path.local.sysfind('libffi-8.dll')
516 if sys.platform == 'win32' and not libffi:
517 raise RuntimeError('could not find libffi')
518 elif libffi:
519 target = os.getcwd() + r'\libffi-8.dll'
520 if not os.path.exists(target):
521 # in tests, we can mock using windows without libffi
522 shutil.copyfile(str(libffi), target)
523 self.c_entryp = newexename
524 self.log.info("created: %s" % (self.c_entryp,))
525
526 @taskdef(['source_c'], "Compiling c source")
527 def task_compile_c(self):
528 """ Compile the generated C code using either makefile or
529 translator/platform
530 """
531 cbuilder = self.cbuilder
532 kwds = {}
533 if self.standalone and self.exe_name is not None:
534 kwds['exe_name'] = self.compute_exe_name().basename
535 cbuilder.compile(**kwds)
536
537 if self.standalone:
538 self.c_entryp = cbuilder.executable_name
539 self.create_exe()
540 else:
541 self.c_entryp = cbuilder.get_entry_point()
542
543 @taskdef([STACKCHECKINSERTION, '?'+BACKENDOPT, RTYPE], "LLInterpreting")
544 def task_llinterpret_lltype(self):
545 from rpython.rtyper.llinterp import LLInterpreter
546
547 translator = self.translator
548 interp = LLInterpreter(translator.rtyper)
549 bk = translator.annotator.bookkeeper
550 graph = bk.getdesc(self.entry_point).getuniquegraph()
551 v = interp.eval_graph(graph,
552 self.extra.get('get_llinterp_args',
553 lambda: [])())
554
555 log.llinterpret("result -> %s" % v)
556
557 def proceed(self, goals):
558 if not goals:
559 if self.default_goal:
560 goals = [self.default_goal]
561 else:
562 self.log.info("nothing to do")
563 return
564 elif isinstance(goals, str):
565 goals = [goals]
566 goals.extend(self.extra_goals)
567 goals = self.backend_select_goals(goals)
568 result = self._execute(goals, task_skip = self._maybe_skip())
569 self.log.info('usession directory: %s' % (udir,))
570 return result
571
572 @classmethod
573 def from_targetspec(cls, targetspec_dic, config=None, args=None,
574 empty_translator=None,
575 disable=[],
576 default_goal=None):
577 if args is None:
578 args = []
579
580 driver = cls(config=config, default_goal=default_goal,
581 disable=disable)
582 target = targetspec_dic['target']
583 driver.timer.start_event("loading target")
584 spec = target(driver, args)
585 driver.timer.end_event("loading target")
586
587 try:
588 entry_point, inputtypes, policy = spec
589 except TypeError:
590 # not a tuple at all
591 entry_point = spec
592 inputtypes = policy = None
593 except ValueError:
594 policy = None
595 entry_point, inputtypes = spec
596
597
598 driver.setup(entry_point, inputtypes,
599 policy=policy,
600 extra=targetspec_dic,
601 empty_translator=empty_translator)
602 return driver
603
604 def prereq_checkpt_rtype(self):
605 assert 'rpython.rtyper.rmodel' not in sys.modules, (
606 "cannot fork because the rtyper has already been imported")
607 prereq_checkpt_rtype_lltype = prereq_checkpt_rtype
608
609 # checkpointing support
610 def _event(self, kind, goal, func):
611 if kind == 'planned' and func.task_earlycheck:
612 func.task_earlycheck(self)
613 if kind == 'pre':
614 fork_before = self.config.translation.fork_before
615 if fork_before:
616 fork_before, = self.backend_select_goals([fork_before])
617 if not fork_before in self.done and fork_before == goal:
618 prereq = getattr(self, 'prereq_checkpt_%s' % goal, None)
619 if prereq:
620 prereq()
621 from rpython.translator.goal import unixcheckpoint
622 unixcheckpoint.restartable_point(auto='run')
623
624 if os.name == 'posix':
625 def shutil_copy(src, dst):
626 # this version handles the case where 'dst' is an executable
627 # currently being executed
628 shutil.copy(src, dst + '~')
629 os.rename(dst + '~', dst)
630 else:
631 shutil_copy = shutil.copy