Debian Codegraph @

rpython/jit/codewriter/call.py

raw symbols SCIP
1 #
2 # Contains the logic to decide, based on the policy, which graphs
3 # to transform to JitCodes or not.
4 #
5 from __future__ import print_function
6
7 from rpython.jit.codewriter import support
8 from rpython.jit.codewriter.jitcode import JitCode
9 from rpython.jit.codewriter.effectinfo import (VirtualizableAnalyzer,
10 QuasiImmutAnalyzer, RandomEffectsAnalyzer, effectinfo_from_writeanalyze,
11 EffectInfo, CallInfoCollection)
12 from rpython.rtyper.lltypesystem import lltype, llmemory
13 from rpython.rtyper.lltypesystem.lltype import getfunctionptr
14 from rpython.rlib import rposix
15 from rpython.translator.backendopt.canraise import RaiseAnalyzer
16 from rpython.translator.backendopt.writeanalyze import ReadWriteAnalyzer
17 from rpython.translator.backendopt.graphanalyze import DependencyTracker
18 from rpython.translator.backendopt.collectanalyze import CollectAnalyzer
19
20
21 class CallControl(object):
22 virtualref_info = None # optionally set from outside
23 has_libffi_call = False # default value
24
25 def __init__(self, cpu=None, jitdrivers_sd=[]):
26 assert isinstance(jitdrivers_sd, list) # debugging
27 self.cpu = cpu
28 self.jitdrivers_sd = jitdrivers_sd
29 self.jitcodes = {} # map {graph: jitcode}
30 self.unfinished_graphs = [] # list of graphs with pending jitcodes
31 self.callinfocollection = CallInfoCollection()
32 if hasattr(cpu, 'rtyper'): # for tests
33 self.rtyper = cpu.rtyper
34 translator = self.rtyper.annotator.translator
35 self.raise_analyzer = RaiseAnalyzer(translator)
36 self.raise_analyzer_ignore_memoryerror = RaiseAnalyzer(translator)
37 self.raise_analyzer_ignore_memoryerror.do_ignore_memory_error()
38 self.readwrite_analyzer = ReadWriteAnalyzer(translator)
39 self.virtualizable_analyzer = VirtualizableAnalyzer(translator)
40 self.quasiimmut_analyzer = QuasiImmutAnalyzer(translator)
41 self.randomeffects_analyzer = RandomEffectsAnalyzer(translator)
42 self.collect_analyzer = CollectAnalyzer(translator)
43 self.seen_rw = DependencyTracker(self.readwrite_analyzer)
44 self.seen_gc = DependencyTracker(self.collect_analyzer)
45 #
46 for index, jd in enumerate(jitdrivers_sd):
47 jd.index = index
48
49 def find_all_graphs(self, policy):
50 try:
51 return self.candidate_graphs
52 except AttributeError:
53 pass
54
55 is_candidate = policy.look_inside_graph
56
57 assert len(self.jitdrivers_sd) > 0
58 todo = [jd.portal_graph for jd in self.jitdrivers_sd]
59 if hasattr(self, 'rtyper'):
60 for oopspec_name, ll_args, ll_res in support.inline_calls_to:
61 c_func, _ = support.builtin_func_for_spec(self.rtyper,
62 oopspec_name,
63 ll_args, ll_res)
64 todo.append(c_func.value._obj.graph)
65 candidate_graphs = set(todo)
66
67 def callers():
68 graph = top_graph
69 print(graph)
70 while graph in coming_from:
71 graph = coming_from[graph]
72 print('<-', graph)
73 coming_from = {}
74
75 while todo:
76 top_graph = todo.pop()
77 for _, op in top_graph.iterblockops():
78 if op.opname not in ("direct_call", "indirect_call"):
79 continue
80 kind = self.guess_call_kind(op, is_candidate)
81 # use callers() to view the calling chain in pdb
82 if kind != "regular":
83 continue
84 for graph in self.graphs_from(op, is_candidate):
85 if graph in candidate_graphs:
86 continue
87 assert is_candidate(graph)
88 todo.append(graph)
89 candidate_graphs.add(graph)
90 coming_from[graph] = top_graph
91 self.candidate_graphs = candidate_graphs
92 return candidate_graphs
93
94 def graphs_from(self, op, is_candidate=None):
95 if is_candidate is None:
96 is_candidate = self.is_candidate
97 if op.opname == 'direct_call':
98 funcobj = op.args[0].value._obj
99 graph = funcobj.graph
100 if is_candidate(graph):
101 return [graph] # common case: look inside this graph
102 else:
103 assert op.opname == 'indirect_call'
104 graphs = op.args[-1].value
105 if graphs is not None:
106 result = []
107 for graph in graphs:
108 if is_candidate(graph):
109 result.append(graph)
110 if result:
111 return result # common case: look inside these graphs,
112 # and ignore the others if there are any
113 # residual call case: we don't need to look into any graph
114 return None
115
116 def guess_call_kind(self, op, is_candidate=None):
117 if op.opname == 'direct_call':
118 funcptr = op.args[0].value
119 if self.jitdriver_sd_from_portal_runner_ptr(funcptr) is not None:
120 return 'recursive'
121 funcobj = funcptr._obj
122 assert (funcobj is not rposix._get_errno and
123 funcobj is not rposix._set_errno), (
124 "the JIT must never come close to _get_errno() or _set_errno();"
125 " it should all be done at a lower level")
126 if getattr(funcobj, 'graph', None) is None:
127 return 'residual'
128 targetgraph = funcobj.graph
129 if hasattr(targetgraph, 'func'):
130 # must never produce JitCode for a function with
131 # _gctransformer_hint_close_stack_ set!
132 if getattr(targetgraph.func,
133 '_gctransformer_hint_close_stack_', False):
134 return 'residual'
135 if hasattr(targetgraph.func, 'oopspec'):
136 return 'builtin'
137 if self.graphs_from(op, is_candidate) is None:
138 return 'residual'
139 return 'regular'
140
141 def is_candidate(self, graph):
142 # used only after find_all_graphs()
143 return graph in self.candidate_graphs
144
145 def grab_initial_jitcodes(self):
146 for jd in self.jitdrivers_sd:
147 jd.mainjitcode = self.get_jitcode(jd.portal_graph)
148 jd.mainjitcode.jitdriver_sd = jd
149
150 def enum_pending_graphs(self):
151 while self.unfinished_graphs:
152 graph = self.unfinished_graphs.pop()
153 yield graph, self.jitcodes[graph]
154
155 def get_jitcode(self, graph, called_from=None):
156 # 'called_from' is only one of the callers, used for debugging.
157 try:
158 return self.jitcodes[graph]
159 except KeyError:
160 # must never produce JitCode for a function with
161 # _gctransformer_hint_close_stack_ set!
162 if hasattr(graph, 'func') and getattr(graph.func,
163 '_gctransformer_hint_close_stack_', False):
164 raise AssertionError(
165 '%s has _gctransformer_hint_close_stack_' % (graph,))
166 #
167 fnaddr, calldescr = self.get_jitcode_calldescr(graph)
168 jitcode = JitCode(graph.name, fnaddr, calldescr,
169 called_from=called_from)
170 self.jitcodes[graph] = jitcode
171 self.unfinished_graphs.append(graph)
172 return jitcode
173
174 def get_jitcode_calldescr(self, graph):
175 """Return the calldescr that describes calls to the 'graph'.
176 This returns a calldescr that is appropriate to attach to the
177 jitcode corresponding to 'graph'. It has no extra effectinfo,
178 because it is not needed there; it is only used by the blackhole
179 interp to really do the call corresponding to 'inline_call' ops.
180 """
181 fnptr = getfunctionptr(graph)
182 FUNC = lltype.typeOf(fnptr).TO
183 fnaddr = llmemory.cast_ptr_to_adr(fnptr)
184 NON_VOID_ARGS = [ARG for ARG in FUNC.ARGS if ARG is not lltype.Void]
185 calldescr = self.cpu.calldescrof(FUNC, tuple(NON_VOID_ARGS),
186 FUNC.RESULT, EffectInfo.MOST_GENERAL)
187 return (fnaddr, calldescr)
188
189 def _raise_effect_error(self, op, extraeffect, functype, calling_graph):
190 explanation = []
191 if extraeffect == EffectInfo.EF_RANDOM_EFFECTS:
192 explanation = self.randomeffects_analyzer.explain_analyze_slowly(op)
193 elif extraeffect == EffectInfo.EF_FORCES_VIRTUAL_OR_VIRTUALIZABLE:
194 explanation = self.virtualizable_analyzer.explain_analyze_slowly(op)
195 msg = []
196 if explanation:
197 msg = [
198 "_______ ERROR AT BOTTOM ______",
199 "RPython callstack leading to problem:",
200 ]
201 msg.extend(explanation)
202 msg.append("_______ ERROR: ______")
203 msg.append("operation %r" % op)
204 msg.append("in graph %s" % (calling_graph or "<unknown>"))
205 msg.append("this calls a %s function," % (functype, ))
206 msg.append(" but this contradicts other sources (e.g. it can have random"
207 " effects): EF=%s" % (extraeffect, ))
208 raise Exception("\n".join(msg))
209
210 def getcalldescr(self, op, oopspecindex=EffectInfo.OS_NONE,
211 extraeffect=None, extradescr=None,
212 calling_graph=None):
213 """Return the calldescr that describes all calls done by 'op'.
214 This returns a calldescr that we can put in the corresponding
215 call operation in the calling jitcode. It gets an effectinfo
216 describing the effect of the call: which field types it may
217 change, whether it can force virtualizables, whether it can
218 raise, etc.
219 """
220 NON_VOID_ARGS = [x.concretetype for x in op.args[1:]
221 if x.concretetype is not lltype.Void]
222 RESULT = op.result.concretetype
223 # check the number and type of arguments
224 FUNC = op.args[0].concretetype.TO
225 ARGS = FUNC.ARGS
226 if NON_VOID_ARGS != [T for T in ARGS if T is not lltype.Void]:
227 raise Exception(
228 "operation %r in %s: calling a function with signature %r, "
229 "but passing actual arguments (ignoring voids) of types %r"
230 % (op, calling_graph, FUNC, NON_VOID_ARGS))
231 if RESULT != FUNC.RESULT:
232 raise Exception(
233 "%r in %s: calling a function with signature %r, "
234 "but the actual return type is %r" % (op, calling_graph, FUNC, RESULT))
235 # ok
236 # get the 'elidable' and 'loopinvariant' flags from the function object
237 elidable = False
238 loopinvariant = False
239 call_release_gil_target = EffectInfo._NO_CALL_RELEASE_GIL_TARGET
240 if op.opname == "direct_call":
241 funcobj = op.args[0].value._obj
242 assert getattr(funcobj, 'calling_conv', 'c') == 'c', (
243 "%r in %s: getcalldescr() with a non-default call ABI" % (op, calling_graph))
244 assert getattr(funcobj, 'natural_arity', -1) == -1, (
245 "JIT backend does not support natural_arity calls, please wrap it in a helper")
246 func = getattr(funcobj, '_callable', None)
247 elidable = getattr(func, "_elidable_function_", False)
248 loopinvariant = getattr(func, "_jit_loop_invariant_", False)
249 if loopinvariant:
250 assert not NON_VOID_ARGS, ("arguments not supported for "
251 "loop-invariant function!")
252 if getattr(func, "_call_aroundstate_target_", None):
253 tgt_func, tgt_saveerr = func._call_aroundstate_target_
254 assert getattr(tgt_func._obj, 'natural_arity', -1) == -1, (
255 "JIT backend does not support natural_arity calls, please wrap it in a helper")
256 tgt_func = llmemory.cast_ptr_to_adr(tgt_func)
257 call_release_gil_target = (tgt_func, tgt_saveerr)
258
259 elif op.opname == 'indirect_call':
260 # check that we're not trying to call indirectly some
261 # function with the special flags
262 graphs = op.args[-1].value
263 for graph in (graphs or ()):
264 if not hasattr(graph, 'func'):
265 continue
266 error = None
267 if hasattr(graph.func, '_elidable_function_'):
268 error = '@jit.elidable'
269 if hasattr(graph.func, '_jit_loop_invariant_'):
270 error = '@jit.loop_invariant'
271 if hasattr(graph.func, '_call_aroundstate_target_'):
272 error = '_call_aroundstate_target_'
273 if not error:
274 continue
275 raise Exception(
276 "%r in %s is an indirect call to a family of functions "
277 "(or methods) that includes %r. However, the latter "
278 "is marked %r. You need to use an indirection: replace "
279 "it with a non-marked function/method which calls the "
280 "marked function." % (op, calling_graph, graph, error))
281 # build the extraeffect
282 random_effects = self.randomeffects_analyzer.analyze(op)
283 if random_effects:
284 extraeffect = EffectInfo.EF_RANDOM_EFFECTS
285 # random_effects implies can_invalidate
286 can_invalidate = random_effects or self.quasiimmut_analyzer.analyze(op)
287 if extraeffect is None:
288 if self.virtualizable_analyzer.analyze(op):
289 extraeffect = EffectInfo.EF_FORCES_VIRTUAL_OR_VIRTUALIZABLE
290 elif loopinvariant:
291 extraeffect = EffectInfo.EF_LOOPINVARIANT
292 elif elidable:
293 cr = self._canraise(op)
294 if cr == "mem":
295 extraeffect = EffectInfo.EF_ELIDABLE_OR_MEMORYERROR
296 elif cr:
297 extraeffect = EffectInfo.EF_ELIDABLE_CAN_RAISE
298 else:
299 extraeffect = EffectInfo.EF_ELIDABLE_CANNOT_RAISE
300 elif self._canraise(op): # True or "mem"
301 extraeffect = EffectInfo.EF_CAN_RAISE
302 else:
303 extraeffect = EffectInfo.EF_CANNOT_RAISE
304 #
305 # check that the result is really as expected
306 if loopinvariant:
307 if extraeffect != EffectInfo.EF_LOOPINVARIANT:
308 self._raise_effect_error(op, extraeffect, "_jit_loop_invariant_", calling_graph)
309 if elidable:
310 if extraeffect not in (EffectInfo.EF_ELIDABLE_CANNOT_RAISE,
311 EffectInfo.EF_ELIDABLE_OR_MEMORYERROR,
312 EffectInfo.EF_ELIDABLE_CAN_RAISE):
313
314 self._raise_effect_error(op, extraeffect, "elidable", calling_graph)
315 elif RESULT is lltype.Void:
316 raise Exception(
317 "operation %r in %s: this calls an elidable function "
318 "but the function has no result" % (op, calling_graph))
319 #
320 effectinfo = effectinfo_from_writeanalyze(
321 self.readwrite_analyzer.analyze(op, self.seen_rw), self.cpu,
322 extraeffect, oopspecindex, can_invalidate, call_release_gil_target,
323 extradescr, self.collect_analyzer.analyze(op, self.seen_gc),
324 )
325 #
326 assert effectinfo is not None
327 if elidable or loopinvariant:
328 assert (effectinfo.extraeffect <
329 EffectInfo.EF_FORCES_VIRTUAL_OR_VIRTUALIZABLE)
330 # XXX this should also say assert not can_invalidate, but
331 # it can't because our analyzer is not good enough for now
332 # (and getexecutioncontext() can't really invalidate)
333 #
334 return self.cpu.calldescrof(FUNC, tuple(NON_VOID_ARGS), RESULT,
335 effectinfo)
336
337 def _canraise(self, op):
338 """Returns True, False, or "mem" to mean 'only MemoryError'."""
339 if op.opname == 'pseudo_call_cannot_raise':
340 return False
341 try:
342 if self.raise_analyzer.can_raise(op):
343 if self.raise_analyzer_ignore_memoryerror.can_raise(op):
344 return True
345 else:
346 return "mem"
347 else:
348 return False
349 except lltype.DelayedPointer:
350 return True # if we need to look into the delayed ptr that is
351 # the portal, then it's certainly going to raise
352
353 def calldescr_canraise(self, calldescr):
354 effectinfo = calldescr.get_extra_info()
355 return effectinfo.check_can_raise()
356
357 def jitdriver_sd_from_portal_graph(self, graph):
358 for jd in self.jitdrivers_sd:
359 if jd.portal_graph is graph:
360 return jd
361 return None
362
363 def jitdriver_sd_from_portal_runner_ptr(self, funcptr):
364 for jd in self.jitdrivers_sd:
365 if funcptr is jd.portal_runner_ptr:
366 return jd
367 return None
368
369 def jitdriver_sd_from_jitdriver(self, jitdriver):
370 for jd in self.jitdrivers_sd:
371 if jd.jitdriver is jitdriver:
372 return jd
373 return None
374
375 def get_vinfo(self, VTYPEPTR):
376 seen = set()
377 for jd in self.jitdrivers_sd:
378 if jd.virtualizable_info is not None:
379 if jd.virtualizable_info.is_vtypeptr(VTYPEPTR):
380 seen.add(jd.virtualizable_info)
381 if seen:
382 assert len(seen) == 1
383 return seen.pop()
384 else:
385 return None
386
387 def could_be_green_field(self, GTYPE, fieldname):
388 GTYPE_fieldname = (GTYPE, fieldname)
389 for jd in self.jitdrivers_sd:
390 if jd.greenfield_info is not None:
391 if GTYPE_fieldname in jd.greenfield_info.green_fields:
392 return True
393 return False