Debian Codegraph @

rpython/jit/metainterp/warmstate.py

raw symbols SCIP
1 import sys
2 import weakref
3
4 from rpython.jit.codewriter import support, longlong
5 from rpython.jit.metainterp import resoperation, history, jitexc
6 from rpython.jit.metainterp.support import ptr2int, int2adr
7 from rpython.rlib.debug import debug_start, debug_stop, debug_print
8 from rpython.rlib.debug import have_debug_prints_for
9 from rpython.rlib.jit import PARAMETERS
10 from rpython.rlib.rjitlog import rjitlog as jl
11 from rpython.rlib.nonconst import NonConstant
12 from rpython.rlib.objectmodel import specialize, we_are_translated, r_dict
13 from rpython.rlib.rarithmetic import intmask, r_uint
14 from rpython.rlib.unroll import unrolling_iterable
15 from rpython.rlib import rstack
16 from rpython.rtyper.annlowlevel import (hlstr, cast_base_ptr_to_instance,
17 cast_object_to_ptr)
18 from rpython.rtyper.lltypesystem import lltype, llmemory, rstr, rffi
19
20 # ____________________________________________________________
21
22 @specialize.arg(0)
23 def specialize_value(TYPE, x):
24 """'x' must be a Signed, a GCREF or a FLOATSTORAGE.
25 This function casts it to a more specialized type, like Char or Ptr(..).
26 """
27 INPUT = lltype.typeOf(x)
28 if INPUT is lltype.Signed:
29 if isinstance(TYPE, lltype.Ptr) and TYPE.TO._gckind == 'raw':
30 # non-gc pointer
31 return rffi.cast(TYPE, x)
32 elif TYPE is lltype.SingleFloat:
33 return longlong.int2singlefloat(x)
34 else:
35 return lltype.cast_primitive(TYPE, x)
36 elif INPUT is longlong.FLOATSTORAGE:
37 if longlong.is_longlong(TYPE):
38 return rffi.cast(TYPE, x)
39 assert TYPE is lltype.Float
40 return longlong.getrealfloat(x)
41 else:
42 return lltype.cast_opaque_ptr(TYPE, x)
43
44 @specialize.ll()
45 def unspecialize_value(value):
46 """Casts 'value' to a Signed, a GCREF or a FLOATSTORAGE."""
47 if isinstance(lltype.typeOf(value), lltype.Ptr):
48 if lltype.typeOf(value).TO._gckind == 'gc':
49 return lltype.cast_opaque_ptr(llmemory.GCREF, value)
50 else:
51 return ptr2int(value)
52 elif isinstance(value, float):
53 return longlong.getfloatstorage(value)
54 else:
55 return lltype.cast_primitive(lltype.Signed, value)
56
57 @specialize.arg(0)
58 def unwrap(TYPE, box):
59 if TYPE is lltype.Void:
60 return None
61 if isinstance(TYPE, lltype.Ptr):
62 if TYPE.TO._gckind == "gc":
63 return box.getref(TYPE)
64 else:
65 adr = int2adr(box.getint())
66 return llmemory.cast_adr_to_ptr(adr, TYPE)
67 if TYPE == lltype.Float:
68 return box.getfloat()
69 else:
70 return lltype.cast_primitive(TYPE, box.getint())
71
72 @specialize.ll()
73 def wrap(cpu, value, inputarg_position_or_neg):
74 assert isinstance(inputarg_position_or_neg, int)
75 if isinstance(lltype.typeOf(value), lltype.Ptr):
76 if lltype.typeOf(value).TO._gckind == 'gc':
77 value = lltype.cast_opaque_ptr(llmemory.GCREF, value)
78 if inputarg_position_or_neg < 0:
79 return history.ConstPtr(value)
80 else:
81 return history.RefFrontendOp(inputarg_position_or_neg, value)
82 else:
83 value = ptr2int(value)
84 # fall through to the end of the function
85 elif (isinstance(value, float) or
86 longlong.is_longlong(lltype.typeOf(value))):
87 if isinstance(value, float):
88 value = longlong.getfloatstorage(value)
89 else:
90 value = rffi.cast(lltype.SignedLongLong, value)
91 if inputarg_position_or_neg < 0:
92 return history.ConstFloat(value)
93 else:
94 return history.FloatFrontendOp(inputarg_position_or_neg, value)
95 elif isinstance(value, str) or isinstance(value, unicode):
96 assert len(value) == 1 # must be a character
97 value = ord(value)
98 elif lltype.typeOf(value) is lltype.SingleFloat:
99 value = longlong.singlefloat2int(value)
100 else:
101 value = intmask(value)
102 if inputarg_position_or_neg < 0:
103 return history.ConstInt(value)
104 else:
105 return history.IntFrontendOp(inputarg_position_or_neg, value)
106
107 @specialize.arg(0)
108 def equal_whatever(TYPE, x, y):
109 if isinstance(TYPE, lltype.Ptr):
110 if TYPE.TO is rstr.STR or TYPE.TO is rstr.UNICODE:
111 return rstr.LLHelpers.ll_streq(x, y)
112 return x == y
113
114 @specialize.arg(0)
115 def hash_whatever(TYPE, x):
116 # Hash of lltype object.
117 # Only supports strings, unicodes and regular instances,
118 # as well as primitives that can meaningfully be cast to Signed.
119 if isinstance(TYPE, lltype.Ptr) and TYPE.TO._gckind == 'gc':
120 if TYPE.TO is rstr.STR or TYPE.TO is rstr.UNICODE:
121 return rstr.LLHelpers.ll_strhash(x) # assumed not null
122 else:
123 if x:
124 return lltype.identityhash(x)
125 else:
126 return 0
127 else:
128 return rffi.cast(lltype.Signed, x)
129
130
131 JC_TRACING = 0x01
132 JC_DONT_TRACE_HERE = 0x02
133 JC_TEMPORARY = 0x04
134 JC_TRACING_OCCURRED= 0x08
135 JC_FORCE_FINISH = 0x10
136
137 class BaseJitCell(object):
138 """Subclasses of BaseJitCell are used in tandem with the single
139 JitCounter instance to record places in the JIT-tracked user program
140 where something particular occurs with the JIT. For some
141 'greenkeys' (e.g. Python bytecode position), we create one instance
142 of JitCell and attach it to that greenkey. This is implemented
143 with jitcounter.install_new_cell(), but conceptually you can think
144 about JitCode instances as attached to some locations of the
145 app-level Python code.
146
147 We create subclasses of BaseJitCell --one per jitdriver-- so that
148 they can store greenkeys of different types.
149
150 Note that we don't create a JitCell the first time we see a given
151 greenkey position in the interpreter. At first, we only hash the
152 greenkey and use that in the JitCounter to record the number of
153 times we have seen it. We only create a JitCell when the
154 JitCounter's total time value reaches 1.0 and we are starting to
155 JIT-compile.
156
157 A JitCell has a 'wref_procedure_token' that is non-None when we
158 actually have a compiled procedure for that greenkey. (It is a
159 weakref, so that it could later be freed; in this case the JitCell
160 will likely be reclaimed a bit later by 'should_remove_jitcell()'.)
161
162 There are other less-common cases where we also create a JitCell: to
163 record some long-term flags about the greenkey. In general, a
164 JitCell can have any combination of the following flags set:
165
166 JC_TRACING: we are now tracing the loop from this greenkey.
167 We'll likely end up with a wref_procedure_token, soonish.
168
169 JC_TRACING_OCCURRED: set if JC_TRACING was set at least once.
170
171 JC_TEMPORARY: a "temporary" wref_procedure_token.
172 It's the procedure_token of a dummy loop that simply calls
173 back the interpreter. Used for a CALL_ASSEMBLER where the
174 target was not compiled yet. In this situation we are still
175 ticking the JitCounter for the same hash, until we reach the
176 threshold and start tracing the loop in earnest.
177
178 JC_DONT_TRACE_HERE: when tracing, don't inline calls to
179 this particular function. (We only set this flag when aborting
180 due to a trace too long, so we use the same flag as a hint to
181 also mean "please trace from here as soon as possible".)
182
183 JC_FORCE_FINISH: when from a cell with that flag set, if the trace
184 becomes too long, "segment" it, ie finish it with a guard_always_fails.
185 this prevents re-tracing and failing this again and again.
186 """
187 flags = 0 # JC_xxx flags
188 wref_procedure_token = None
189 next = None
190
191 def get_procedure_token(self):
192 if self.wref_procedure_token is not None:
193 token = self.wref_procedure_token()
194 if token and not token.invalidated:
195 return token
196 return None
197
198 def has_seen_a_procedure_token(self):
199 return self.wref_procedure_token is not None
200
201 def set_procedure_token(self, token, tmp=False):
202 self.wref_procedure_token = self._makeref(token)
203 if tmp:
204 self.flags |= JC_TEMPORARY
205 else:
206 self.flags &= ~JC_TEMPORARY
207
208 def _makeref(self, token):
209 assert token is not None
210 return weakref.ref(token)
211
212 def should_remove_jitcell(self):
213 if self.get_procedure_token() is not None:
214 return False # don't remove JitCells with a procedure_token
215 if self.flags & JC_TRACING:
216 return False # don't remove JitCells that are being traced
217 if self.flags & JC_DONT_TRACE_HERE:
218 # if we have this flag, and we *had* a procedure_token but
219 # we no longer have one, then remove me. this prevents this
220 # JitCell from being immortal.
221 return self.has_seen_a_procedure_token() # i.e. dead weakref
222 if self.flags & JC_FORCE_FINISH:
223 # don't remove, we need to remember that we should really finish a
224 # trace for this
225 return False
226 return True # Other JitCells can be removed.
227
228 # ____________________________________________________________
229
230
231 class WarmEnterState(object):
232
233 def __init__(self, warmrunnerdesc, jitdriver_sd):
234 "NOT_RPYTHON"
235 self.warmrunnerdesc = warmrunnerdesc
236 self.jitdriver_sd = jitdriver_sd
237 if warmrunnerdesc is not None: # for tests
238 self.cpu = warmrunnerdesc.cpu
239 try:
240 self.profiler = warmrunnerdesc.metainterp_sd.profiler
241 except AttributeError: # for tests
242 self.profiler = None
243 # initialize the state with the default values of the
244 # parameters specified in rlib/jit.py
245 if self.warmrunnerdesc is not None:
246 for name, default_value in PARAMETERS.items():
247 meth = getattr(self, 'set_param_' + name)
248 meth(default_value)
249
250 def _compute_threshold(self, threshold):
251 return self.warmrunnerdesc.jitcounter.compute_threshold(threshold)
252
253 def set_param_threshold(self, threshold):
254 self.increment_threshold = self._compute_threshold(threshold)
255
256 def set_param_function_threshold(self, threshold):
257 self.increment_function_threshold = self._compute_threshold(threshold)
258
259 def set_param_trace_eagerness(self, value):
260 self.increment_trace_eagerness = self._compute_threshold(value)
261
262 def set_param_trace_limit(self, value):
263 if value < 0:
264 raise ValueError
265 if value > 100000000:
266 raise ValueError
267 self.trace_limit = value
268
269 def set_param_decay(self, decay):
270 self.warmrunnerdesc.jitcounter.set_decay(decay)
271
272 def set_param_inlining(self, value):
273 self.inlining = value
274
275 def set_param_disable_unrolling(self, value):
276 self.disable_unrolling_threshold = value
277
278 def set_param_enable_opts(self, value):
279 from rpython.jit.metainterp.optimizeopt import ALL_OPTS_DICT, ALL_OPTS_NAMES
280
281 d = {}
282 if NonConstant(False):
283 value = 'blah' # not a constant ''
284 if value is None or value == 'all':
285 value = ALL_OPTS_NAMES
286 for name in value.split(":"):
287 if name:
288 if name not in ALL_OPTS_DICT:
289 raise ValueError('Unknown optimization ' + name)
290 d[name] = None
291 self.enable_opts = d
292
293 def set_param_loop_longevity(self, value):
294 # note: it's a global parameter, not a per-jitdriver one
295 if (self.warmrunnerdesc is not None and
296 self.warmrunnerdesc.memory_manager is not None): # all for tests
297 self.warmrunnerdesc.memory_manager.set_max_age(value)
298
299 def set_param_retrace_limit(self, value):
300 if self.warmrunnerdesc:
301 if self.warmrunnerdesc.memory_manager:
302 self.warmrunnerdesc.memory_manager.retrace_limit = value
303
304 def set_param_pureop_historylength(self, value):
305 self.pureop_historylength = value
306
307 def set_param_max_retrace_guards(self, value):
308 if self.warmrunnerdesc:
309 if self.warmrunnerdesc.memory_manager:
310 self.warmrunnerdesc.memory_manager.max_retrace_guards = value
311
312 def set_param_max_unroll_loops(self, value):
313 if self.warmrunnerdesc:
314 if self.warmrunnerdesc.memory_manager:
315 self.warmrunnerdesc.memory_manager.max_unroll_loops = value
316
317 def set_param_max_unroll_recursion(self, value):
318 if self.warmrunnerdesc:
319 if self.warmrunnerdesc.memory_manager:
320 self.warmrunnerdesc.memory_manager.max_unroll_recursion = value
321
322 def set_param_vec(self, ivalue):
323 self.vec = bool(ivalue)
324
325 def set_param_vec_all(self, ivalue):
326 self.vec_all = bool(ivalue)
327
328 def set_param_vec_cost(self, ivalue):
329 self.vec_cost = ivalue
330
331 def disable_noninlinable_function(self, greenkey):
332 cell = self.JitCell.ensure_jit_cell_at_key(greenkey)
333 cell.flags |= JC_DONT_TRACE_HERE
334 debug_start("jit-disableinlining")
335 loc = self.get_location_str(greenkey)
336 debug_print("disabled inlining", loc)
337 debug_stop("jit-disableinlining")
338
339 def attach_procedure_to_interp(self, greenkey, procedure_token):
340 cell = self.JitCell.ensure_jit_cell_at_key(greenkey)
341 old_token = cell.get_procedure_token()
342 cell.set_procedure_token(procedure_token)
343 if old_token is not None:
344 self.cpu.redirect_call_assembler(old_token, procedure_token)
345 # procedure_token is also kept alive by any loop that used
346 # to point to old_token. Actually freeing old_token early
347 # is a pointless optimization (it is tiny).
348 old_token.record_jump_to(procedure_token)
349
350 # ----------
351
352 def make_entry_point(self):
353 "NOT_RPYTHON"
354 from rpython.jit.metainterp import compile
355 if hasattr(self, 'entry_point_fns'):
356 return self.entry_point_fns
357
358 warmrunnerdesc = self.warmrunnerdesc
359 metainterp_sd = warmrunnerdesc.metainterp_sd
360 jitdriver_sd = self.jitdriver_sd
361 vinfo = jitdriver_sd.virtualizable_info
362 index_of_virtualizable = jitdriver_sd.index_of_virtualizable
363 num_green_args = jitdriver_sd.num_green_args
364 JitCell = self.make_jitcell_subclass()
365 self.make_jitdriver_callbacks()
366 confirm_enter_jit = self.confirm_enter_jit
367 range_red_args = unrolling_iterable(
368 range(num_green_args, num_green_args + jitdriver_sd.num_red_args))
369 name_red_args = unrolling_iterable(
370 [(i, 'arg%d' % i) for i in range(jitdriver_sd.num_red_args)])
371 # get a new specialized copy of the method
372 ARGS = []
373 for kind in jitdriver_sd.red_args_types:
374 if kind == 'int':
375 ARGS.append(lltype.Signed)
376 elif kind == 'ref':
377 ARGS.append(llmemory.GCREF)
378 elif kind == 'float':
379 ARGS.append(longlong.FLOATSTORAGE)
380 else:
381 assert 0, kind
382 func_execute_token = self.cpu.make_execute_token(*ARGS)
383 cpu = self.cpu
384 jitcounter = self.warmrunnerdesc.jitcounter
385 result_type = jitdriver_sd.result_type
386
387 def execute_assembler(loop_token, *args):
388 # Call the backend to run the 'looptoken' with the given
389 # input args.
390
391 # If we have a virtualizable, we have to clear its
392 # state, to make sure we enter with vable_token being NONE
393 #
394 if vinfo is not None:
395 virtualizable = args[index_of_virtualizable]
396 vinfo.clear_vable_token(virtualizable)
397
398 deadframe = func_execute_token(loop_token, *args)
399 #
400 # Record in the memmgr that we just ran this loop,
401 # so that it will keep it alive for a longer time
402 warmrunnerdesc.memory_manager.keep_loop_alive(loop_token)
403 #
404 # Handle the failure
405 fail_descr = cpu.get_latest_descr(deadframe)
406 # First, a fast path to avoid raising and immediately catching
407 # a DoneWithThisFrame exception
408 if result_type == history.VOID:
409 if isinstance(fail_descr, compile.DoneWithThisFrameDescrVoid):
410 return None
411 if result_type == history.INT:
412 if isinstance(fail_descr, compile.DoneWithThisFrameDescrInt):
413 return fail_descr.get_result(cpu, deadframe)
414 if result_type == history.REF:
415 if isinstance(fail_descr, compile.DoneWithThisFrameDescrRef):
416 return fail_descr.get_result(cpu, deadframe)
417 if result_type == history.FLOAT:
418 if isinstance(fail_descr, compile.DoneWithThisFrameDescrFloat):
419 return fail_descr.get_result(cpu, deadframe)
420 #
421 # General case
422 fail_descr.handle_fail(deadframe, metainterp_sd, jitdriver_sd)
423 assert 0, "should have raised"
424
425 def bound_reached(hash, cell, *args):
426 from rpython.jit.metainterp.pyjitpl import MetaInterp
427 if not confirm_enter_jit(*args):
428 return
429 jitcounter.decay_all_counters()
430 if rstack.stack_almost_full():
431 return
432 greenargs = args[:num_green_args]
433 if cell is None:
434 cell = JitCell(*greenargs)
435 jitcounter.install_new_cell(hash, cell)
436 # start tracing
437 metainterp = MetaInterp(
438 metainterp_sd, jitdriver_sd,
439 force_finish_trace=bool(cell.flags & JC_FORCE_FINISH))
440 cell.flags |= JC_TRACING | JC_TRACING_OCCURRED
441 try:
442 metainterp.compile_and_run_once(jitdriver_sd, *args)
443 finally:
444 cell.flags &= ~JC_TRACING
445
446 def maybe_compile_and_run(increment_threshold, *args):
447 """Entry point to the JIT. Called at the point with the
448 can_enter_jit() hint, and at the start of a function
449 with a different threshold.
450 """
451 if increment_threshold == 0:
452 return # jit is off
453 # Look for the cell corresponding to the current greenargs.
454 # Search for the JitCell that is of the correct subclass of
455 # BaseJitCell, and that stores a key that compares equal.
456 # These few lines inline some logic that is also on the
457 # JitCell class, to avoid computing the hash several times.
458 greenargs = args[:num_green_args]
459 hash = JitCell.get_uhash(*greenargs)
460 cell = jitcounter.lookup_chain(hash)
461 while cell is not None:
462 if isinstance(cell, JitCell) and cell.comparekey(*greenargs):
463 break # found
464 cell = cell.next
465 else:
466 # not found. increment the counter
467 if jitcounter.tick(hash, increment_threshold):
468 bound_reached(hash, None, *args)
469 return
470
471 # Here, we have found 'cell'.
472 #
473 if cell.flags & (JC_TRACING | JC_TEMPORARY):
474 if cell.flags & JC_TRACING:
475 # tracing already happening in some outer invocation of
476 # this function. don't trace a second time.
477 return
478 # attached by compile_tmp_callback(). count normally
479 if jitcounter.tick(hash, increment_threshold):
480 bound_reached(hash, cell, *args)
481 return
482 # machine code was already compiled for these greenargs
483 procedure_token = cell.get_procedure_token()
484 if procedure_token is None:
485 if cell.flags & JC_DONT_TRACE_HERE:
486 if not cell.has_seen_a_procedure_token():
487 # A JC_DONT_TRACE_HERE, i.e. a non-inlinable function.
488 # If we never tried to trace it, try it now immediately.
489 # Otherwise, count normally.
490 if cell.flags & JC_TRACING_OCCURRED:
491 tick = jitcounter.tick(hash, increment_threshold)
492 else:
493 tick = True
494 if tick:
495 bound_reached(hash, cell, *args)
496 return
497 # it was an aborted compilation, or maybe a weakref that
498 # has been freed
499 jitcounter.cleanup_chain(hash)
500 return
501 if not confirm_enter_jit(*args):
502 return
503 # extract and unspecialize the red arguments to pass to
504 # the assembler
505 execute_args = ()
506 for i in range_red_args:
507 execute_args += (unspecialize_value(args[i]), )
508 # run it, but from outside in ll_portal_runner, not from here
509 # (this avoids RPython-level recursion with no corresponding
510 # app-level recursion, as shown by issues 2200 and 2335)
511 raise EnterJitAssembler(procedure_token, *execute_args)
512
513 class EnterJitAssembler(jitexc.JitException):
514 def __init__(self, procedure_token, *args):
515 self.procedure_token = procedure_token
516 for i, argname in name_red_args:
517 setattr(self, argname, args[i])
518 def execute(self):
519 args = ()
520 for i, argname in name_red_args:
521 args += (getattr(self, argname), )
522 return execute_assembler(self.procedure_token, *args)
523
524 maybe_compile_and_run._dont_inline_ = True
525 self.execute_assembler = execute_assembler
526 self.entry_point_fns = (maybe_compile_and_run,
527 EnterJitAssembler)
528 return self.entry_point_fns
529
530 # ----------
531
532 def make_unwrap_greenkey(self):
533 "NOT_RPYTHON"
534 if hasattr(self, 'unwrap_greenkey'):
535 return self.unwrap_greenkey
536 #
537 jitdriver_sd = self.jitdriver_sd
538 green_args_spec = unrolling_iterable(jitdriver_sd._green_args_spec)
539 #
540 def unwrap_greenkey(greenkey):
541 greenargs = ()
542 i = 0
543 for TYPE in green_args_spec:
544 greenbox = greenkey[i]
545 assert isinstance(greenbox, history.Const)
546 value = unwrap(TYPE, greenbox)
547 greenargs += (value,)
548 i = i + 1
549 return greenargs
550 #
551 unwrap_greenkey._always_inline_ = True
552 self.unwrap_greenkey = unwrap_greenkey
553 return unwrap_greenkey
554
555 # ----------
556
557 def make_jitcell_subclass(self):
558 "NOT_RPYTHON"
559 if hasattr(self, 'JitCell'):
560 return self.JitCell
561 #
562 jitcounter = self.warmrunnerdesc.jitcounter
563 jitdriver_sd = self.jitdriver_sd
564 green_args_name_spec = unrolling_iterable([('g%d' % i, TYPE)
565 for i, TYPE in enumerate(jitdriver_sd._green_args_spec)])
566 unwrap_greenkey = self.make_unwrap_greenkey()
567 #
568 class JitCell(BaseJitCell):
569 def __init__(self, *greenargs):
570 i = 0
571 for attrname, _ in green_args_name_spec:
572 setattr(self, attrname, greenargs[i])
573 i = i + 1
574
575 def comparekey(self, *greenargs2):
576 i = 0
577 for attrname, TYPE in green_args_name_spec:
578 item1 = getattr(self, attrname)
579 if not equal_whatever(TYPE, item1, greenargs2[i]):
580 return False
581 i = i + 1
582 return True
583
584 @staticmethod
585 def get_uhash(*greenargs):
586 x = r_uint(-1888132534)
587 i = 0
588 for _, TYPE in green_args_name_spec:
589 item = greenargs[i]
590 y = r_uint(hash_whatever(TYPE, item))
591 x = (x ^ y) * r_uint(1405695061) # prime number, 2**30~31
592 i = i + 1
593 return x
594
595 @staticmethod
596 def get_jitcell(*greenargs):
597 hash = JitCell.get_uhash(*greenargs)
598 cell = jitcounter.lookup_chain(hash)
599 while cell is not None:
600 if (isinstance(cell, JitCell) and
601 cell.comparekey(*greenargs)):
602 return cell
603 cell = cell.next
604 return None
605
606 @staticmethod
607 def get_jit_cell_at_key(greenkey):
608 greenargs = unwrap_greenkey(greenkey)
609 return JitCell.get_jitcell(*greenargs)
610
611 @staticmethod
612 def trace_next_iteration(greenkey):
613 greenargs = unwrap_greenkey(greenkey)
614 JitCell._trace_next_iteration(*greenargs)
615
616 @staticmethod
617 def _trace_next_iteration(*greenargs):
618 hash = JitCell.get_uhash(*greenargs)
619 jitcounter.change_current_fraction(hash, 0.98)
620
621 @staticmethod
622 def trace_next_iteration_hash(hash):
623 jitcounter.change_current_fraction(hash, 0.98)
624
625 @staticmethod
626 def ensure_jit_cell_at_key(greenkey):
627 greenargs = unwrap_greenkey(greenkey)
628 return JitCell._ensure_jit_cell_at_key(*greenargs)
629
630 @staticmethod
631 def _ensure_jit_cell_at_key(*greenargs):
632 hash = JitCell.get_uhash(*greenargs)
633 cell = jitcounter.lookup_chain(hash)
634 while cell is not None:
635 if (isinstance(cell, JitCell) and
636 cell.comparekey(*greenargs)):
637 return cell
638 cell = cell.next
639 newcell = JitCell(*greenargs)
640 jitcounter.install_new_cell(hash, newcell)
641 return newcell
642
643 @staticmethod
644 def dont_trace_here(*greenargs):
645 cell = JitCell._ensure_jit_cell_at_key(*greenargs)
646 cell.flags |= JC_DONT_TRACE_HERE
647
648 @staticmethod
649 def mark_as_being_traced(*greenargs):
650 cell = JitCell._ensure_jit_cell_at_key(*greenargs)
651 cell.flags |= JC_TRACING
652 #
653 self.JitCell = JitCell
654 return JitCell
655
656 # ----------
657
658 def make_jitdriver_callbacks(self):
659 if hasattr(self, 'get_location_str'):
660 return
661 #
662 warmrunnerdesc = self.warmrunnerdesc
663 unwrap_greenkey = self.make_unwrap_greenkey()
664 JitCell = self.make_jitcell_subclass()
665 jd = self.jitdriver_sd
666 cpu = self.cpu
667 rtyper = self.warmrunnerdesc.rtyper
668
669 def can_inline_callable(greenkey):
670 greenargs = unwrap_greenkey(greenkey)
671 if can_never_inline(*greenargs):
672 return False
673 cell = JitCell.get_jitcell(*greenargs)
674 if cell is not None and (cell.flags & JC_DONT_TRACE_HERE) != 0:
675 return False
676 return True
677 self.can_inline_callable = can_inline_callable
678
679 def dont_trace_here(greenkey):
680 # Set greenkey as somewhere that tracing should not occur into;
681 # notice that, as per the description of JC_DONT_TRACE_HERE earlier,
682 # if greenkey hasn't been traced separately, setting
683 # JC_DONT_TRACE_HERE will force tracing the next time the function
684 # is encountered.
685 cell = JitCell.ensure_jit_cell_at_key(greenkey)
686 cell.flags |= JC_DONT_TRACE_HERE
687 self.dont_trace_here = dont_trace_here
688
689 def mark_as_being_traced(greenkey):
690 cell = JitCell.ensure_jit_cell_at_key(greenkey)
691 cell.flags |= JC_TRACING
692 self.mark_as_being_traced = mark_as_being_traced
693
694 def mark_force_finish_tracing(greenkey):
695 """ mark greenkey as "please definitely finish a trace for it the
696 next time" """
697 cell = JitCell.ensure_jit_cell_at_key(greenkey)
698 cell.flags |= JC_FORCE_FINISH
699 self.mark_force_finish_tracing = mark_force_finish_tracing
700
701 if jd._should_unroll_one_iteration_ptr is None:
702 def should_unroll_one_iteration(greenkey):
703 return False
704 else:
705 inline_ptr = jd._should_unroll_one_iteration_ptr
706 def should_unroll_one_iteration(greenkey):
707 greenargs = unwrap_greenkey(greenkey)
708 fn = support.maybe_on_top_of_llinterp(rtyper, inline_ptr)
709 return fn(*greenargs)
710 self.should_unroll_one_iteration = should_unroll_one_iteration
711
712 redargtypes = ''.join([kind[0] for kind in jd.red_args_types])
713
714 def get_assembler_token(greenkey):
715 cell = JitCell.ensure_jit_cell_at_key(greenkey)
716 procedure_token = cell.get_procedure_token()
717 if procedure_token is None:
718 from rpython.jit.metainterp.compile import compile_tmp_callback
719 memmgr = warmrunnerdesc.memory_manager
720 procedure_token = compile_tmp_callback(cpu, jd, greenkey,
721 redargtypes, memmgr)
722 cell.set_procedure_token(procedure_token, tmp=True)
723 return procedure_token
724 self.get_assembler_token = get_assembler_token
725
726 #
727 jitdriver = self.jitdriver_sd.jitdriver
728 if self.jitdriver_sd.jitdriver:
729 drivername = jitdriver.name
730 else:
731 drivername = '<unknown jitdriver>'
732 # get_location returns
733 get_location_ptr = getattr(self.jitdriver_sd, '_get_location_ptr', None)
734 if get_location_ptr is not None:
735 types = self.jitdriver_sd._get_loc_types
736 unwrap_greenkey = self.make_unwrap_greenkey()
737 unrolled_types = unrolling_iterable(enumerate(types))
738 def get_location(greenkey):
739 greenargs = unwrap_greenkey(greenkey)
740 fn = support.maybe_on_top_of_llinterp(rtyper, get_location_ptr)
741 value_tuple = fn(*greenargs)
742 values = []
743 for i, (sem_type,gen_type) in unrolled_types:
744 if gen_type == "s":
745 value = getattr(value_tuple, 'item' + str(i))
746 values.append(jl.wrap(sem_type,gen_type,hlstr(value)))
747 elif gen_type == "i":
748 value = getattr(value_tuple, 'item' + str(i))
749 values.append(jl.wrap(sem_type,gen_type,intmask(value)))
750 else:
751 raise NotImplementedError
752 return values
753 self.get_location_types = list(types)
754 self.get_location = get_location
755 else:
756 self.get_location_types = None
757 self.get_location = None
758 #
759 printable_loc_ptr = self.jitdriver_sd._get_printable_location_ptr
760 if printable_loc_ptr is None:
761 missing = '(%s: no get_printable_location)' % drivername
762 def get_location_str(greenkey):
763 return missing
764 else:
765 unwrap_greenkey = self.make_unwrap_greenkey()
766 # the following missing text should not be seen, as it is
767 # returned only if debug_prints are currently not enabled,
768 # but it may show up anyway (consider it bugs)
769 missing = ('(%s: get_printable_location '
770 'disabled, no debug_print)' % drivername)
771 #
772 def get_location_str(greenkey):
773 if not have_debug_prints_for("jit-"):
774 return missing
775 greenargs = unwrap_greenkey(greenkey)
776 fn = support.maybe_on_top_of_llinterp(rtyper, printable_loc_ptr)
777 llres = fn(*greenargs)
778 if not we_are_translated() and isinstance(llres, str):
779 return llres
780 return hlstr(llres)
781 self.get_location_str = get_location_str
782 #
783 confirm_enter_jit_ptr = self.jitdriver_sd._confirm_enter_jit_ptr
784 if confirm_enter_jit_ptr is None:
785 def confirm_enter_jit(*args):
786 return True
787 else:
788 #
789 def confirm_enter_jit(*args):
790 fn = support.maybe_on_top_of_llinterp(rtyper,
791 confirm_enter_jit_ptr)
792 return fn(*args)
793 self.confirm_enter_jit = confirm_enter_jit
794 #
795 can_never_inline_ptr = self.jitdriver_sd._can_never_inline_ptr
796 if can_never_inline_ptr is None:
797 def can_never_inline(*greenargs):
798 return False
799 else:
800 #
801 def can_never_inline(*greenargs):
802 fn = support.maybe_on_top_of_llinterp(rtyper,
803 can_never_inline_ptr)
804 return fn(*greenargs)
805 self.can_never_inline = can_never_inline
806 get_unique_id_ptr = self.jitdriver_sd._get_unique_id_ptr
807 def get_unique_id(greenkey):
808 greenargs = unwrap_greenkey(greenkey)
809 fn = support.maybe_on_top_of_llinterp(rtyper, get_unique_id_ptr)
810 return fn(*greenargs)
811 self.get_unique_id = get_unique_id