Debian Codegraph @

pypy/module/pypyjit/interp_jit.py

raw symbols SCIP
1 """This is not the JIT :-)
2
3 This is transformed to become a JIT by code elsewhere: rpython/jit/*
4 """
5
6 from rpython.rlib.rarithmetic import r_uint, intmask
7 from rpython.rlib.jit import JitDriver, hint, we_are_jitted, dont_look_inside
8 from rpython.rlib import jit, jit_hooks
9 from rpython.rlib.rjitlog import rjitlog as jl
10 from rpython.rlib.jit import current_trace_length, unroll_parameters,\
11 JitHookInterface
12 from rpython.rtyper.annlowlevel import cast_instance_to_gcref
13 import pypy.interpreter.pyopcode # for side-effects
14 from pypy.interpreter.error import OperationError, oefmt
15 from pypy.interpreter.pycode import CO_GENERATOR, CO_COROUTINE, PyCode
16 from pypy.interpreter.gateway import unwrap_spec
17 from pypy.interpreter.pyframe import PyFrame
18 from pypy.interpreter.pyopcode import Yield, Return
19 from pypy.interpreter.baseobjspace import W_Root
20 from pypy.interpreter.typedef import TypeDef
21 from pypy.interpreter.gateway import interp2app
22 from opcode import opmap
23
24
25 PyFrame._virtualizable_ = ['last_instr', 'pycode',
26 'valuestackdepth',
27 'locals_cells_stack_w[*]',
28 'debugdata',
29 'w_globals',
30 ]
31
32 JUMP_ABSOLUTE = opmap['JUMP_ABSOLUTE']
33
34 def get_printable_location(next_instr, is_being_profiled, bytecode):
35 from pypy.tool.stdlib_opcode import opcode_method_names
36 from pypy.interpreter.pytraceback import offset2lineno
37 bytecode_name = opcode_method_names[ord(bytecode.co_code[next_instr])]
38 lineno = offset2lineno(bytecode, intmask(next_instr))
39 return '%s;%s:%d-%d~#%d %s' % (
40 bytecode.co_name, bytecode.co_filename, bytecode.co_firstlineno,
41 lineno, next_instr, bytecode_name)
42
43 def get_unique_id(next_instr, is_being_profiled, bytecode):
44 from rpython.rlib import rvmprof
45 return rvmprof.get_unique_id(bytecode)
46
47 @jl.returns(jl.MP_FILENAME, jl.MP_LINENO,
48 jl.MP_SCOPE, jl.MP_INDEX, jl.MP_OPCODE)
49 def get_location(next_instr, is_being_profiled, bytecode):
50 from pypy.tool.stdlib_opcode import opcode_method_names
51 from pypy.interpreter.pytraceback import offset2lineno
52 bcindex = ord(bytecode.co_code[next_instr])
53 opname = ""
54 if 0 <= bcindex < len(opcode_method_names):
55 opname = opcode_method_names[bcindex]
56 name = bytecode.co_name
57 if not name:
58 name = ""
59 line = offset2lineno(bytecode, intmask(next_instr))
60 return (bytecode.co_filename, line,
61 name, intmask(next_instr), opname)
62
63 def should_unroll_one_iteration(next_instr, is_being_profiled, bytecode):
64 return (bytecode.co_flags & (CO_COROUTINE | CO_GENERATOR)) != 0
65
66 class PyPyJitDriver(JitDriver):
67 reds = ['frame', 'ec']
68 greens = ['next_instr', 'is_being_profiled', 'pycode']
69 virtualizables = ['frame']
70
71 pypyjitdriver = PyPyJitDriver(get_printable_location = get_printable_location,
72 get_location = get_location,
73 get_unique_id = get_unique_id,
74 should_unroll_one_iteration =
75 should_unroll_one_iteration,
76 name='pypyjit',
77 is_recursive=True)
78
79 class __extend__(PyFrame):
80
81 def dispatch(self, pycode, next_instr, ec):
82 self = hint(self, access_directly=True)
83 next_instr = r_uint(next_instr)
84 is_being_profiled = self.get_is_being_profiled()
85 try:
86 while True:
87 pypyjitdriver.jit_merge_point(ec=ec,
88 frame=self, next_instr=next_instr, pycode=pycode,
89 is_being_profiled=is_being_profiled)
90 co_code = pycode.co_code
91 self.valuestackdepth = hint(self.valuestackdepth, promote=True)
92 next_instr = self.handle_bytecode(co_code, next_instr, ec)
93 is_being_profiled = self.get_is_being_profiled()
94 except Yield:
95 w_result = self.popvalue()
96 jit.hint(self, force_virtualizable=True)
97 return w_result
98 except Return:
99 return self.popvalue()
100
101 def jump_absolute(self, jumpto, next_instr, ec):
102 jumpto *= 2
103 if jumpto >= next_instr: # no backward jump, just normal
104 return jumpto
105 if we_are_jitted():
106 #
107 # assume that only threads are using the bytecode counter
108 decr_by = 0
109 if self.space.actionflag.has_bytecode_counter: # constant-folded
110 if self.space.threadlocals.gil_ready: # quasi-immutable field
111 decr_by = _get_adapted_tick_counter()
112 #
113 self.last_instr = intmask(jumpto)
114 ec.bytecode_trace(self, decr_by)
115 jumpto = r_uint(self.last_instr)
116 #
117 pypyjitdriver.can_enter_jit(frame=self, ec=ec, next_instr=jumpto,
118 pycode=self.getcode(),
119 is_being_profiled=self.get_is_being_profiled())
120 return jumpto
121
122 def _get_adapted_tick_counter():
123 # Normally, the tick counter is decremented by 100 for every
124 # Python opcode. Here, to better support JIT compilation of
125 # small loops, we decrement it by a possibly smaller constant.
126 # We get the maximum 100 when the (unoptimized) trace length
127 # is at least 3200 (a bit randomly).
128 trace_length = r_uint(current_trace_length())
129 decr_by = trace_length // 32
130 if decr_by < 1:
131 decr_by = 1
132 elif decr_by > 100: # also if current_trace_length() returned -1
133 decr_by = 100
134 return intmask(decr_by)
135
136
137 # ____________________________________________________________
138 #
139 # Public interface
140
141 def set_param(space, __args__):
142 '''Configure the tunable JIT parameters.
143 * set_param(name=value, ...) # as keyword arguments
144 * set_param("name=value,name=value") # as a user-supplied string
145 * set_param("off") # disable the jit
146 * set_param("default") # restore all defaults
147 '''
148 # XXXXXXXXX
149 args_w, kwds_w = __args__.unpack()
150 if len(args_w) > 1:
151 raise oefmt(space.w_TypeError,
152 "set_param() takes at most 1 non-keyword argument, %d "
153 "given", len(args_w))
154 if len(args_w) == 1:
155 text = space.text_w(args_w[0])
156 try:
157 jit.set_user_param(None, text)
158 except ValueError:
159 raise oefmt(space.w_ValueError, "error in JIT parameters string")
160 for key, w_value in kwds_w.items():
161 if key == 'enable_opts':
162 jit.set_param(None, 'enable_opts', space.text_w(w_value))
163 else:
164 intval = space.int_w(w_value)
165 for name, _ in unroll_parameters:
166 if name == key and name != 'enable_opts':
167 jit.set_param(None, name, intval)
168 break
169 else:
170 raise oefmt(space.w_TypeError, "no JIT parameter '%s'", key)
171
172 @dont_look_inside
173 def residual_call(space, w_callable, __args__):
174 '''For testing. Invokes callable(...), but without letting
175 the JIT follow the call.'''
176 return space.call_args(w_callable, __args__)
177
178
179 class W_NotFromAssembler(W_Root):
180 def __init__(self, space, w_callable):
181 self.space = space
182 self.w_callable = w_callable
183 def descr_call(self, __args__):
184 _call_not_in_trace(self.space, self.w_callable, __args__)
185 return self
186
187 @jit.not_in_trace
188 def _call_not_in_trace(space, w_callable, __args__):
189 # this _call_not_in_trace() must return None
190 space.call_args(w_callable, __args__)
191
192 def not_from_assembler_new(space, w_subtype, w_callable):
193 return W_NotFromAssembler(space, w_callable)
194
195 W_NotFromAssembler.typedef = TypeDef("not_from_assembler",
196 __doc__ = """\
197 A decorator that returns a callable that invokes the original
198 callable, but not from the JIT-produced assembler. It is called
199 from the interpreted mode, and from the JIT creation (pyjitpl) or
200 exiting (blackhole) steps, but just not from the final assembler.
201
202 Note that the return value of the callable is ignored, because
203 there is no reasonable way to guess what it should be in case the
204 function is not called. Instead, calling the callable returns
205 the callable itself, for convenience (see below).
206
207 This is meant to be used notably in sys.settrace() for coverage-
208 like tools. For that purpose, if g = not_from_assembler(f), then
209 'g(*args)' may call 'f(*args)' or not. As g() always returns g
210 itself, you can directly set sys.settrace(g).
211 """,
212 __new__ = interp2app(not_from_assembler_new),
213 __call__ = interp2app(W_NotFromAssembler.descr_call),
214 )
215 W_NotFromAssembler.typedef.acceptable_as_base_class = False
216
217 @unwrap_spec(next_instr=int, is_being_profiled=int, w_pycode=PyCode)
218 @dont_look_inside
219 def get_jitcell_at_key(space, next_instr, is_being_profiled, w_pycode):
220 ll_pycode = cast_instance_to_gcref(w_pycode)
221 return space.newbool(bool(jit_hooks.get_jitcell_at_key(
222 'pypyjit', r_uint(next_instr), int(bool(is_being_profiled)), ll_pycode)))
223
224 @unwrap_spec(next_instr=int, is_being_profiled=int, w_pycode=PyCode)
225 @dont_look_inside
226 def dont_trace_here(space, next_instr, is_being_profiled, w_pycode):
227 """ Don't trace here means don't inline this function. Look into mark_as_being_traced
228 for not tracing inside a loop
229 """
230 ll_pycode = cast_instance_to_gcref(w_pycode)
231 jit_hooks.dont_trace_here(
232 'pypyjit', r_uint(next_instr), int(bool(is_being_profiled)), ll_pycode)
233 return space.w_None
234
235 @unwrap_spec(next_instr=int, is_being_profiled=int, w_pycode=PyCode)
236 @dont_look_inside
237 def mark_as_being_traced(space, next_instr, is_being_profiled, w_pycode):
238 """ Mark this position as "being traced". Has a side effect of not
239 starting new tracing
240 """
241 ll_pycode = cast_instance_to_gcref(w_pycode)
242 jit_hooks.mark_as_being_traced(
243 'pypyjit', r_uint(next_instr), int(is_being_profiled), ll_pycode)
244 return space.w_None
245
246
247 @unwrap_spec(next_instr=int, is_being_profiled=bool, w_pycode=PyCode)
248 @dont_look_inside
249 def trace_next_iteration(space, next_instr, is_being_profiled, w_pycode):
250 ll_pycode = cast_instance_to_gcref(w_pycode)
251 jit_hooks.trace_next_iteration(
252 'pypyjit', r_uint(next_instr), int(bool(is_being_profiled)), ll_pycode)
253 return space.w_None
254
255 @unwrap_spec(hash=r_uint)
256 @dont_look_inside
257 def trace_next_iteration_hash(space, hash):
258 jit_hooks.trace_next_iteration_hash('pypyjit', hash)
259 return space.w_None
260
261 @dont_look_inside
262 def releaseall(space):
263 """ Mark all current machine code objects as ready to release. They will
264 be released at the next GC (unless they are currently in use in the stack
265 of one of the threads). Doing pypyjit.releaseall(); gc.collect() is a
266 heavy hammer that forces the JIT roughly to the state of a newly started
267 PyPy.
268 """
269 jit_hooks.stats_memmgr_release_all(None)
270
271 # class Cache(object):
272 # in_recursion = False
273
274 # def __init__(self, space):
275 # self.w_compile_bridge = space.w_None
276 # self.w_compile_loop = space.w_None
277
278 # def set_compile_bridge(space, w_hook):
279 # cache = space.fromcache(Cache)
280 # assert w_hook is not None
281 # cache.w_compile_bridge = w_hook
282
283 # def set_compile_loop(space, w_hook):
284 # from rpython.rlib.nonconst import NonConstant
285
286 # cache = space.fromcache(Cache)
287 # assert w_hook is not None
288 # cache.w_compile_loop = w_hook
289 # cache.in_recursion = NonConstant(False)
290
291 # class PyPyJitHookInterface(JitHookInterface):
292 # def after_compile(self, debug_info):
293 # space = self.space
294 # cache = space.fromcache(Cache)
295 # if cache.in_recursion:
296 # return
297 # l_w = []
298 # if not space.is_true(cache.w_compile_loop):
299 # return
300 # for i, op in enumerate(debug_info.operations):
301 # if op.is_guard():
302 # w_t = space.newtuple([space.newint(i), space.newint(op.getopnum()), space.newint(op.getdescr().get_jitcounter_hash())])
303 # l_w.append(w_t)
304 # try:
305 # cache.in_recursion = True
306 # try:
307 # space.call_function(cache.w_compile_loop, space.newlist(l_w))
308 # except OperationError, e:
309 # e.write_unraisable(space, "jit hook ", cache.w_compile_bridge)
310 # finally:
311 # cache.in_recursion = False
312
313 # def after_compile_bridge(self, debug_info):
314 # space = self.space
315 # cache = space.fromcache(Cache)
316 # if cache.in_recursion:
317 # return
318 # if not space.is_true(cache.w_compile_bridge):
319 # return
320 # w_hash = space.newint(debug_info.fail_descr.get_jitcounter_hash())
321 # try:
322 # cache.in_recursion = True
323 # try:
324 # space.call_function(cache.w_compile_bridge, w_hash)
325 # except OperationError, e:
326 # e.write_unraisable(space, "jit hook ", cache.w_compile_bridge)
327 # finally:
328 # cache.in_recursion = False
329
330 # def before_compile(self, debug_info):
331 # pass
332
333 # def before_compile_bridge(self, debug_info):
334 # pass
335
336 # pypy_hooks = PyPyJitHookInterface()
337