Debian Codegraph @

rpython/jit/codewriter/jtransform.py

raw symbols SCIP
1 import py
2
3 from rpython.jit.codewriter import support, heaptracker, longlong
4 from rpython.jit.codewriter.effectinfo import EffectInfo
5 from rpython.jit.codewriter.flatten import ListOfKind, IndirectCallTargets
6 from rpython.jit.codewriter.policy import log
7 from rpython.jit.metainterp import quasiimmut
8 from rpython.jit.metainterp.history import getkind
9 from rpython.jit.metainterp.blackhole import BlackholeInterpreter
10 from rpython.jit.metainterp.support import ptr2int
11 from rpython.flowspace.model import SpaceOperation, Variable, Constant
12 from rpython.rlib import objectmodel
13 from rpython.rlib.jit import _we_are_jitted
14 from rpython.rlib.rgc import lltype_is_gc
15 from rpython.rtyper.lltypesystem import lltype, llmemory, rstr, rffi
16 from rpython.rtyper.lltypesystem import rbytearray
17 from rpython.rtyper import rclass
18 from rpython.rtyper.rclass import IR_QUASIIMMUTABLE, IR_QUASIIMMUTABLE_ARRAY
19 from rpython.translator.unsimplify import varoftype
20
21 class UnsupportedMallocFlags(Exception):
22 pass
23
24 def transform_graph(graph, cpu=None, callcontrol=None, portal_jd=None):
25 """Transform a control flow graph to make it suitable for
26 being flattened in a JitCode.
27 """
28 constant_fold_ll_issubclass(graph, cpu)
29 t = Transformer(cpu, callcontrol, portal_jd)
30 t.transform(graph)
31
32 def constant_fold_ll_issubclass(graph, cpu):
33 # ll_issubclass can be inserted by the inliner to check exception types.
34 # See corner case metainterp.test.test_exception:test_catch_different_class
35 if cpu is None:
36 return
37 excmatch = cpu.rtyper.exceptiondata.fn_exception_match
38 for block in list(graph.iterblocks()):
39 for i, op in enumerate(block.operations):
40 if (op.opname == 'direct_call' and
41 all(isinstance(a, Constant) for a in op.args) and
42 op.args[0].value._obj is excmatch._obj):
43 constant_result = excmatch(*[a.value for a in op.args[1:]])
44 block.operations[i] = SpaceOperation(
45 'same_as',
46 [Constant(constant_result, lltype.Bool)],
47 op.result)
48 if block.exitswitch is op.result:
49 block.exitswitch = None
50 block.recloseblock(*[link for link in block.exits
51 if link.exitcase == constant_result])
52
53 def integer_bounds(size, unsigned):
54 if unsigned:
55 return 0, 1 << (8 * size)
56 else:
57 return -(1 << (8 * size - 1)), 1 << (8 * size - 1)
58
59 class Transformer(object):
60 vable_array_vars = None
61
62 def __init__(self, cpu=None, callcontrol=None, portal_jd=None):
63 self.cpu = cpu
64 self.callcontrol = callcontrol
65 self.portal_jd = portal_jd # non-None only for the portal graph(s)
66 self.graph = None
67
68 def transform(self, graph):
69 self.graph = graph
70 for block in list(graph.iterblocks()):
71 self.optimize_block(block)
72
73 def optimize_block(self, block):
74 if block.operations == ():
75 return
76 self.vable_array_vars = {}
77 self.vable_flags = {}
78 renamings = {}
79 renamings_constants = {} # subset of 'renamings', {Var:Const} only
80 newoperations = []
81 #
82 def do_rename(var, var_or_const):
83 if var.concretetype is lltype.Void:
84 renamings[var] = Constant(None, lltype.Void)
85 return
86 renamings[var] = var_or_const
87 if isinstance(var_or_const, Constant):
88 value = var_or_const.value
89 try:
90 value = lltype._cast_whatever(var.concretetype, value)
91 except RuntimeError:
92 return # can happen for unreachable code
93 renamings_constants[var] = Constant(value, var.concretetype)
94 #
95 for op in block.operations:
96 if renamings_constants:
97 op = self._do_renaming(renamings_constants, op)
98 oplist = self.rewrite_operation(op)
99 #
100 count_before_last_operation = len(newoperations)
101 if not isinstance(oplist, list):
102 oplist = [oplist]
103 for op1 in oplist:
104 if isinstance(op1, SpaceOperation):
105 newoperations.append(self._do_renaming(renamings, op1))
106 elif op1 is None:
107 # rewrite_operation() returns None to mean "has no real
108 # effect, the result should just be renamed to args[0]"
109 if op.result is not None:
110 do_rename(op.result, renamings.get(op.args[0],
111 op.args[0]))
112 elif isinstance(op1, Constant):
113 do_rename(op.result, op1)
114 else:
115 raise TypeError(repr(op1))
116 #
117 if block.canraise:
118 if len(newoperations) == count_before_last_operation:
119 self._killed_exception_raising_operation(block)
120 block.operations = newoperations
121 block.exitswitch = renamings.get(block.exitswitch, block.exitswitch)
122 self.follow_constant_exit(block)
123 self.optimize_goto_if_not(block)
124 if isinstance(block.exitswitch, tuple):
125 self._check_no_vable_array(block.exitswitch)
126 for link in block.exits:
127 self._check_no_vable_array(link.args)
128 self._do_renaming_on_link(renamings, link)
129
130 def _do_renaming(self, rename, op):
131 op = SpaceOperation(op.opname, op.args[:], op.result)
132 for i, v in enumerate(op.args):
133 if isinstance(v, Variable):
134 if v in rename:
135 op.args[i] = rename[v]
136 elif isinstance(v, ListOfKind):
137 newlst = []
138 for x in v:
139 if x in rename:
140 x = rename[x]
141 newlst.append(x)
142 op.args[i] = ListOfKind(v.kind, newlst)
143 return op
144
145 def _check_no_vable_array(self, list):
146 if not self.vable_array_vars:
147 return
148 for v in list:
149 if v in self.vable_array_vars:
150 vars = self.vable_array_vars[v]
151 (v_base, arrayfielddescr, arraydescr) = vars
152 raise AssertionError(
153 "A virtualizable array is passed around; it should\n"
154 "only be used immediately after being read. Note\n"
155 "that a possible cause is indexing with an index not\n"
156 "known non-negative, or catching IndexError, or\n"
157 "not inlining at all (for tests: use listops=True).\n"
158 "This is about: %r\n"
159 "Occurred in: %r" % (arrayfielddescr, self.graph))
160 # extra explanation: with the way things are organized in
161 # rpython/rlist.py, the ll_getitem becomes a function call
162 # that is typically meant to be inlined by the JIT, but
163 # this does not work with vable arrays because
164 # jtransform.py expects the getfield and the getarrayitem
165 # to be in the same basic block. It works a bit as a hack
166 # for simple cases where we performed the backendopt
167 # inlining before (even with a very low threshold, because
168 # there is _always_inline_ on the relevant functions).
169
170 def _do_renaming_on_link(self, rename, link):
171 for i, v in enumerate(link.args):
172 if isinstance(v, Variable):
173 if v in rename:
174 link.args[i] = rename[v]
175
176 def _killed_exception_raising_operation(self, block):
177 assert block.exits[0].exitcase is None
178 block.exits = block.exits[:1]
179 block.exitswitch = None
180
181 # ----------
182
183 def follow_constant_exit(self, block):
184 v = block.exitswitch
185 if isinstance(v, Constant) and not block.canraise:
186 llvalue = v.value
187 for link in block.exits:
188 if link.llexitcase == llvalue:
189 break
190 else:
191 assert link.exitcase == 'default'
192 block.exitswitch = None
193 link.exitcase = link.llexitcase = None
194 block.recloseblock(link)
195
196 def optimize_goto_if_not(self, block):
197 """Replace code like 'v = int_gt(x,y); exitswitch = v'
198 with just 'exitswitch = ('int_gt',x,y)'."""
199 if len(block.exits) != 2:
200 return False
201 v = block.exitswitch
202 if (block.canraise or isinstance(v, tuple)
203 or v.concretetype != lltype.Bool):
204 return False
205 for op in block.operations[::-1]:
206 # check if variable is used in block
207 for arg in op.args:
208 if arg == v:
209 return False
210 if isinstance(arg, ListOfKind) and v in arg.content:
211 return False
212 if v is op.result:
213 if op.opname not in ('int_lt', 'int_le', 'int_eq', 'int_ne',
214 'int_gt', 'int_ge',
215 'float_lt', 'float_le', 'float_eq',
216 'float_ne', 'float_gt', 'float_ge',
217 'int_is_zero', 'int_is_true',
218 'ptr_eq', 'ptr_ne',
219 'ptr_iszero', 'ptr_nonzero'):
220 return False # not a supported operation
221 # ok! optimize this case
222 block.operations.remove(op)
223 block.exitswitch = (op.opname,) + tuple(op.args)
224 #if op.opname in ('ptr_iszero', 'ptr_nonzero'):
225 block.exitswitch += ('-live-before',)
226 # if the variable escape to the next block along a link,
227 # replace it with a constant, because we know its value
228 for link in block.exits:
229 while v in link.args:
230 index = link.args.index(v)
231 link.args[index] = Constant(link.llexitcase,
232 lltype.Bool)
233 return True
234 return False
235
236 # ----------
237
238 def rewrite_operation(self, op):
239 try:
240 rewrite = _rewrite_ops[op.opname]
241 except KeyError:
242 raise Exception("the JIT doesn't support the operation %r"
243 " in %r" % (op, getattr(self, 'graph', '?')))
244 return rewrite(self, op)
245
246 def rewrite_op_same_as(self, op):
247 if op.args[0] in self.vable_array_vars:
248 self.vable_array_vars[op.result]= self.vable_array_vars[op.args[0]]
249
250 def rewrite_op_cast_ptr_to_adr(self, op):
251 if lltype_is_gc(op.args[0].concretetype):
252 raise Exception("cast_ptr_to_adr for GC types unsupported")
253
254 def rewrite_op_cast_pointer(self, op):
255 newop = self.rewrite_op_same_as(op)
256 assert newop is None
257 return
258 # disabled for now
259 if (self._is_rclass_instance(op.args[0]) and
260 self._is_rclass_instance(op.result)):
261 FROM = op.args[0].concretetype.TO
262 TO = op.result.concretetype.TO
263 if lltype._castdepth(TO, FROM) > 0:
264 vtable = heaptracker.get_vtable_for_gcstruct(self.cpu, TO)
265 if vtable.subclassrange_max - vtable.subclassrange_min == 1:
266 # it's a precise class check
267 const_vtable = Constant(vtable, lltype.typeOf(vtable))
268 return [None, # hack, do the right renaming from op.args[0] to op.result
269 SpaceOperation("record_exact_class", [op.args[0], const_vtable], None)]
270
271 def rewrite_op_likely(self, op):
272 return None # "no real effect"
273
274 def rewrite_op_unlikely(self, op):
275 return None # "no real effect"
276
277 def rewrite_op_revdb_do_next_call(self, op):
278 return [] # ignored, only for revdb
279
280 def rewrite_op_raw_malloc_usage(self, op):
281 if self.cpu.translate_support_code or isinstance(op.args[0], Variable):
282 return # the operation disappears
283 else:
284 # only for untranslated tests: get a real integer estimate
285 arg = op.args[0].value
286 arg = llmemory.raw_malloc_usage(arg)
287 return [Constant(arg, lltype.Signed)]
288
289 def rewrite_op_jit_record_exact_class(self, op):
290 return SpaceOperation("record_exact_class", [op.args[0], op.args[1]], None)
291
292 def rewrite_op_jit_record_known_result(self, op):
293 for arg in op.args:
294 if getkind(arg.concretetype) == 'float':
295 raise Exception("record_known_result %s does not support floats" % op)
296 # hack: use op.args[0] as the result var, which is correct with regards
297 # to the concretetype, the only thing that getcalldescr accesses
298 callop = SpaceOperation('direct_call', op.args[1:], op.args[0])
299 calldescr = self.callcontrol.getcalldescr(
300 callop,
301 calling_graph=self.graph)
302 assert calldescr.get_extra_info().check_is_elidable()
303 if getkind(op.args[0].concretetype) == "int":
304 opname = "record_known_result_i"
305 else:
306 assert getkind(op.args[0].concretetype) == "ref"
307 opname = "record_known_result_r"
308 op1 = self.rewrite_call(op, opname,
309 op.args[:2], args=op.args[2:],
310 calldescr=calldescr, force_ir=True)
311 if self.callcontrol.calldescr_canraise(calldescr):
312 op1 = [op1, SpaceOperation('-live-', [], None)]
313 return op1
314
315 def rewrite_op_jit_record_exact_value(self, op):
316 if getkind(op.args[0].concretetype) == "int":
317 assert getkind(op.args[1].concretetype) == "int"
318 return SpaceOperation("record_exact_value_i", [op.args[0], op.args[1]], None)
319 else:
320 assert getkind(op.args[0].concretetype) == "ref"
321 assert getkind(op.args[1].concretetype) == "ref"
322 return SpaceOperation("record_exact_value_r", [op.args[0], op.args[1]], None)
323
324 def rewrite_op_debug_assert_not_none(self, op):
325 if isinstance(op.args[0], Variable):
326 return SpaceOperation('assert_not_none', [op.args[0]], None)
327 else:
328 return []
329
330 def rewrite_op_cast_bool_to_int(self, op): pass
331 def rewrite_op_cast_bool_to_uint(self, op): pass
332 def rewrite_op_cast_char_to_int(self, op): pass
333 def rewrite_op_cast_unichar_to_int(self, op): pass
334 def rewrite_op_cast_int_to_char(self, op): pass
335 def rewrite_op_cast_int_to_unichar(self, op): pass
336 def rewrite_op_cast_int_to_uint(self, op): pass
337 def rewrite_op_cast_uint_to_int(self, op): pass
338
339 def _rewrite_symmetric(self, op):
340 """Rewrite 'c1+v2' into 'v2+c1' in an attempt to avoid generating
341 too many variants of the bytecode."""
342 if (isinstance(op.args[0], Constant) and
343 isinstance(op.args[1], Variable)):
344 reversename = {'int_lt': 'int_gt',
345 'int_le': 'int_ge',
346 'int_gt': 'int_lt',
347 'int_ge': 'int_le',
348 'uint_lt': 'uint_gt',
349 'uint_le': 'uint_ge',
350 'uint_gt': 'uint_lt',
351 'uint_ge': 'uint_le',
352 'float_lt': 'float_gt',
353 'float_le': 'float_ge',
354 'float_gt': 'float_lt',
355 'float_ge': 'float_le',
356 }.get(op.opname, op.opname)
357 return SpaceOperation(reversename,
358 [op.args[1], op.args[0]] + op.args[2:],
359 op.result)
360 else:
361 return op
362
363 rewrite_op_int_add = _rewrite_symmetric
364 rewrite_op_int_mul = _rewrite_symmetric
365 rewrite_op_int_and = _rewrite_symmetric
366 rewrite_op_int_or = _rewrite_symmetric
367 rewrite_op_int_xor = _rewrite_symmetric
368 rewrite_op_int_lt = _rewrite_symmetric
369 rewrite_op_int_le = _rewrite_symmetric
370 rewrite_op_int_gt = _rewrite_symmetric
371 rewrite_op_int_ge = _rewrite_symmetric
372 rewrite_op_uint_lt = _rewrite_symmetric
373 rewrite_op_uint_le = _rewrite_symmetric
374 rewrite_op_uint_gt = _rewrite_symmetric
375 rewrite_op_uint_ge = _rewrite_symmetric
376
377 rewrite_op_float_add = _rewrite_symmetric
378 rewrite_op_float_mul = _rewrite_symmetric
379 rewrite_op_float_lt = _rewrite_symmetric
380 rewrite_op_float_le = _rewrite_symmetric
381 rewrite_op_float_gt = _rewrite_symmetric
382 rewrite_op_float_ge = _rewrite_symmetric
383
384 def rewrite_op_int_add_ovf(self, op):
385 op0 = self._rewrite_symmetric(op)
386 op1 = SpaceOperation('-live-', [], None)
387 return [op1, op0]
388
389 rewrite_op_int_mul_ovf = rewrite_op_int_add_ovf
390
391 def rewrite_op_int_sub_ovf(self, op):
392 op1 = SpaceOperation('-live-', [], None)
393 return [op1, op]
394
395 def _noop_rewrite(self, op):
396 return op
397
398 rewrite_op_convert_float_bytes_to_longlong = _noop_rewrite
399 rewrite_op_convert_longlong_bytes_to_float = _noop_rewrite
400 cast_ptr_to_weakrefptr = _noop_rewrite
401 cast_weakrefptr_to_ptr = _noop_rewrite
402
403 # ----------
404 # Various kinds of calls
405
406 def rewrite_op_direct_call(self, op):
407 kind = self.callcontrol.guess_call_kind(op)
408 return getattr(self, 'handle_%s_call' % kind)(op)
409
410 def rewrite_op_indirect_call(self, op):
411 kind = self.callcontrol.guess_call_kind(op)
412 return getattr(self, 'handle_%s_indirect_call' % kind)(op)
413
414 def rewrite_call(self, op, namebase, initialargs, args=None,
415 calldescr=None, force_ir=False):
416 """Turn 'i0 = direct_call(fn, i1, i2, ref1, ref2)'
417 into 'i0 = xxx_call_ir_i(fn, descr, [i1,i2], [ref1,ref2])'.
418 The name is one of '{residual,inline,conditional}_call_{r,ir,irf}_{i,r,f,v}'."""
419 if args is None:
420 args = op.args[1:]
421 self._check_no_vable_array(args)
422 lst_i, lst_r, lst_f = self.make_three_lists(args)
423 reskind = getkind(op.result.concretetype)[0]
424 if lst_f or reskind == 'f': kinds = 'irf'
425 elif lst_i or force_ir: kinds = 'ir'
426 else: kinds = 'r'
427 if force_ir: assert kinds == 'ir' # no 'f'
428 sublists = []
429 if 'i' in kinds: sublists.append(lst_i)
430 if 'r' in kinds: sublists.append(lst_r)
431 if 'f' in kinds: sublists.append(lst_f)
432 if calldescr is not None:
433 sublists.append(calldescr)
434 return SpaceOperation('%s_%s_%s' % (namebase, kinds, reskind),
435 initialargs + sublists, op.result)
436
437 def make_three_lists(self, vars):
438 args_i = []
439 args_r = []
440 args_f = []
441 for v in vars:
442 self.add_in_correct_list(v, args_i, args_r, args_f)
443 return [ListOfKind('int', args_i),
444 ListOfKind('ref', args_r),
445 ListOfKind('float', args_f)]
446
447 def add_in_correct_list(self, v, lst_i, lst_r, lst_f):
448 kind = getkind(v.concretetype)
449 if kind == 'void': return
450 elif kind == 'int': lst = lst_i
451 elif kind == 'ref': lst = lst_r
452 elif kind == 'float': lst = lst_f
453 else: raise AssertionError(kind)
454 lst.append(v)
455
456 def handle_residual_call(self, op, extraargs=[], may_call_jitcodes=False,
457 oopspecindex=EffectInfo.OS_NONE,
458 extraeffect=None,
459 extradescr=None):
460 """A direct_call turns into the operation 'residual_call_xxx' if it
461 is calling a function that we don't want to JIT. The initial args
462 of 'residual_call_xxx' are the function to call, and its calldescr."""
463 calldescr = self.callcontrol.getcalldescr(op, oopspecindex=oopspecindex,
464 extraeffect=extraeffect,
465 extradescr=extradescr,
466 calling_graph=self.graph)
467 op1 = self.rewrite_call(op, 'residual_call',
468 [op.args[0]] + extraargs, calldescr=calldescr)
469 if may_call_jitcodes or self.callcontrol.calldescr_canraise(calldescr):
470 op1 = [op1, SpaceOperation('-live-', [], None)]
471 return op1
472
473 def handle_regular_call(self, op):
474 """A direct_call turns into the operation 'inline_call_xxx' if it
475 is calling a function that we want to JIT. The initial arg of
476 'inline_call_xxx' is the JitCode of the called function."""
477 [targetgraph] = self.callcontrol.graphs_from(op)
478 jitcode = self.callcontrol.get_jitcode(targetgraph,
479 called_from=self.graph)
480 op0 = self.rewrite_call(op, 'inline_call', [jitcode])
481 op1 = SpaceOperation('-live-', [], None)
482 return [op0, op1]
483
484 def handle_builtin_call(self, op):
485 oopspec_name, args = support.decode_builtin_call(op)
486 # dispatch to various implementations depending on the oopspec_name
487 if oopspec_name.startswith('list.') or oopspec_name.startswith('newlist'):
488 prepare = self._handle_list_call
489 elif oopspec_name.startswith('int.'):
490 prepare = self._handle_int_special
491 elif oopspec_name.startswith('stroruni.'):
492 prepare = self._handle_stroruni_call
493 elif oopspec_name == 'str.str2unicode':
494 prepare = self._handle_str2unicode_call
495 elif oopspec_name.startswith('virtual_ref'):
496 prepare = self._handle_virtual_ref_call
497 elif oopspec_name.startswith('jit.'):
498 prepare = self._handle_jit_call
499 elif oopspec_name.startswith('libffi_'):
500 prepare = self._handle_libffi_call
501 elif oopspec_name.startswith('math.sqrt'):
502 prepare = self._handle_math_sqrt_call
503 elif oopspec_name.startswith('rgc.'):
504 prepare = self._handle_rgc_call
505 elif oopspec_name.startswith('rvmprof.'):
506 prepare = self._handle_rvmprof_call
507 elif oopspec_name.endswith('dict.lookup'):
508 # also ordereddict.lookup
509 prepare = self._handle_dict_lookup_call
510 else:
511 prepare = self.prepare_builtin_call
512 try:
513 op1 = prepare(op, oopspec_name, args)
514 except NotSupported:
515 op1 = op
516 # If the resulting op1 is still a direct_call, turn it into a
517 # residual_call.
518 if isinstance(op1, SpaceOperation) and op1.opname == 'direct_call':
519 op1 = self.handle_residual_call(op1)
520 return op1
521
522 def handle_recursive_call(self, op):
523 jitdriver_sd = self.callcontrol.jitdriver_sd_from_portal_runner_ptr(
524 op.args[0].value)
525 assert jitdriver_sd is not None
526 ops = self.promote_greens(op.args[1:], jitdriver_sd.jitdriver)
527 num_green_args = len(jitdriver_sd.jitdriver.greens)
528 args = ([Constant(jitdriver_sd.index, lltype.Signed)] +
529 self.make_three_lists(op.args[1:1+num_green_args]) +
530 self.make_three_lists(op.args[1+num_green_args:]))
531 kind = getkind(op.result.concretetype)[0]
532 op0 = SpaceOperation('recursive_call_%s' % kind, args, op.result)
533 op1 = SpaceOperation('-live-', [], None)
534 return ops + [op0, op1]
535
536 handle_residual_indirect_call = handle_residual_call
537
538 def handle_regular_indirect_call(self, op):
539 """An indirect call where at least one target has a JitCode."""
540 lst = []
541 for targetgraph in self.callcontrol.graphs_from(op):
542 jitcode = self.callcontrol.get_jitcode(targetgraph,
543 called_from=self.graph)
544 lst.append(jitcode)
545 op0 = SpaceOperation('-live-', [], None)
546 op1 = SpaceOperation('int_guard_value', [op.args[0]], None)
547 op2 = self.handle_residual_call(op, [IndirectCallTargets(lst)], True)
548 result = [op0, op1]
549 if isinstance(op2, list):
550 result += op2
551 else:
552 result.append(op2)
553 return result
554
555 def prepare_builtin_call(self, op, oopspec_name, args,
556 extra=None, extrakey=None):
557 argtypes = [v.concretetype for v in args]
558 resulttype = op.result.concretetype
559 c_func, TP = support.builtin_func_for_spec(self.cpu.rtyper,
560 oopspec_name, argtypes,
561 resulttype, extra, extrakey)
562 return SpaceOperation('direct_call', [c_func] + args, op.result)
563
564
565 def _do_builtin_call(self, op, oopspec_name=None, args=None,
566 extra=None, extrakey=None):
567 if oopspec_name is None: oopspec_name = op.opname
568 if args is None: args = op.args
569 op1 = self.prepare_builtin_call(op, oopspec_name, args,
570 extra, extrakey)
571 return self.rewrite_op_direct_call(op1)
572
573 # XXX some of the following functions should not become residual calls
574 # but be really compiled
575 rewrite_op_int_abs = _do_builtin_call
576 rewrite_op_int_floordiv = _do_builtin_call
577 rewrite_op_int_mod = _do_builtin_call
578 rewrite_op_llong_abs = _do_builtin_call
579 rewrite_op_llong_floordiv = _do_builtin_call
580 rewrite_op_llong_mod = _do_builtin_call
581 rewrite_op_ullong_floordiv = _do_builtin_call
582 rewrite_op_ullong_mod = _do_builtin_call
583 rewrite_op_gc_identityhash = _do_builtin_call
584 rewrite_op_gc_id = _do_builtin_call
585 rewrite_op_gc_pin = _do_builtin_call
586 rewrite_op_gc_unpin = _do_builtin_call
587 rewrite_op_cast_float_to_uint = _do_builtin_call
588 rewrite_op_cast_uint_to_float = _do_builtin_call
589 rewrite_op_weakref_create = _do_builtin_call
590 rewrite_op_weakref_deref = _do_builtin_call
591 rewrite_op_gc_add_memory_pressure = _do_builtin_call
592
593 # ----------
594 # getfield/setfield/mallocs etc.
595
596 def rewrite_op_hint(self, op):
597 hints = op.args[1].value
598
599 # hack: if there are both 'promote' and 'promote_string', kill
600 # one of them based on the type of the value
601 if hints.get('promote_string') and hints.get('promote'):
602 hints = hints.copy()
603 if op.args[0].concretetype == lltype.Ptr(rstr.STR):
604 del hints['promote']
605 else:
606 del hints['promote_string']
607
608 if hints.get('promote') and op.args[0].concretetype is not lltype.Void:
609 assert op.args[0].concretetype != lltype.Ptr(rstr.STR)
610 kind = getkind(op.args[0].concretetype)
611 op0 = SpaceOperation('-live-', [], None)
612 op1 = SpaceOperation('%s_guard_value' % kind, [op.args[0]], None)
613 # the special return value None forces op.result to be considered
614 # equal to op.args[0]
615 return [op0, op1, None]
616 if (hints.get('promote_string') and
617 op.args[0].concretetype is not lltype.Void):
618 S = lltype.Ptr(rstr.STR)
619 assert op.args[0].concretetype == S
620 self._register_extra_helper(EffectInfo.OS_STREQ_NONNULL,
621 "str.eq_nonnull",
622 [S, S],
623 lltype.Signed,
624 EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
625 descr, p = self.callcontrol.callinfocollection.callinfo_for_oopspec(
626 EffectInfo.OS_STREQ_NONNULL)
627 # XXX this is fairly ugly way of creating a constant,
628 # however, callinfocollection has no better interface
629 c = Constant(p.adr.ptr, lltype.typeOf(p.adr.ptr))
630 op1 = SpaceOperation('str_guard_value', [op.args[0], c, descr],
631 op.result)
632 return [SpaceOperation('-live-', [], None), op1, None]
633 if (hints.get('promote_unicode') and
634 op.args[0].concretetype is not lltype.Void):
635 U = lltype.Ptr(rstr.UNICODE)
636 assert op.args[0].concretetype == U
637 self._register_extra_helper(EffectInfo.OS_UNIEQ_NONNULL,
638 "str.eq_nonnull",
639 [U, U],
640 lltype.Signed,
641 EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
642 descr, p = self.callcontrol.callinfocollection.callinfo_for_oopspec(
643 EffectInfo.OS_UNIEQ_NONNULL)
644 # XXX this is fairly ugly way of creating a constant,
645 # however, callinfocollection has no better interface
646 c = Constant(p.adr.ptr, lltype.typeOf(p.adr.ptr))
647 op1 = SpaceOperation('str_guard_value', [op.args[0], c, descr],
648 op.result)
649 return [SpaceOperation('-live-', [], None), op1, None]
650 if hints.get('force_virtualizable'):
651 return SpaceOperation('hint_force_virtualizable', [op.args[0]], None)
652 if hints.get('force_no_const'): # for tests only
653 assert getkind(op.args[0].concretetype) == 'int'
654 return SpaceOperation('int_same_as', [op.args[0]], op.result)
655 if hints.get('fresh_virtualizable') or hints.get('access_directly'):
656 return # those are handled, no need to warn
657 log.WARNING('ignoring hint %r at %r' % (hints, self.graph))
658
659 def _rewrite_raw_malloc(self, op, name, args):
660 # NB. the operation 'raw_malloc' is not supported; this is for
661 # the operation 'malloc'/'malloc_varsize' with {flavor: 'gc'}
662 d = op.args[1].value.copy()
663 d.pop('flavor')
664 add_memory_pressure = d.pop('add_memory_pressure', False)
665 zero = d.pop('zero', False)
666 track_allocation = d.pop('track_allocation', True)
667 if d:
668 raise UnsupportedMallocFlags(d)
669 if zero:
670 name += '_zero'
671 if add_memory_pressure:
672 name += '_add_memory_pressure'
673 if not track_allocation:
674 name += '_no_track_allocation'
675 TYPE = op.args[0].value
676 op1 = self.prepare_builtin_call(op, name, args, (TYPE,), TYPE)
677 if name.startswith('raw_malloc_varsize') and TYPE.OF == lltype.Char:
678 return self._handle_oopspec_call(op1, args,
679 EffectInfo.OS_RAW_MALLOC_VARSIZE_CHAR,
680 EffectInfo.EF_CAN_RAISE)
681 return self.rewrite_op_direct_call(op1)
682
683 def rewrite_op_malloc_varsize(self, op):
684 if op.args[1].value['flavor'] == 'raw':
685 return self._rewrite_raw_malloc(op, 'raw_malloc_varsize',
686 [op.args[2]])
687 if op.args[0].value == rstr.STR:
688 return SpaceOperation('newstr', [op.args[2]], op.result)
689 elif op.args[0].value == rstr.UNICODE:
690 return SpaceOperation('newunicode', [op.args[2]], op.result)
691 else:
692 # XXX only strings or simple arrays for now
693 ARRAY = op.args[0].value
694 arraydescr = self.cpu.arraydescrof(ARRAY)
695 if op.args[1].value.get('zero', False):
696 opname = 'new_array_clear'
697 elif ((isinstance(ARRAY.OF, lltype.Ptr) and ARRAY.OF._needsgc()) or
698 isinstance(ARRAY.OF, lltype.Struct)):
699 opname = 'new_array_clear'
700 else:
701 opname = 'new_array'
702 return SpaceOperation(opname, [op.args[2], arraydescr], op.result)
703
704 def zero_contents(self, ops, v, TYPE):
705 if isinstance(TYPE, lltype.Struct):
706 for name, FIELD in TYPE._flds.iteritems():
707 if isinstance(FIELD, lltype.Struct):
708 # substruct
709 self.zero_contents(ops, v, FIELD)
710 else:
711 c_name = Constant(name, lltype.Void)
712 c_null = Constant(FIELD._defl(), FIELD)
713 op = SpaceOperation('setfield', [v, c_name, c_null],
714 None)
715 self.extend_with(ops, self.rewrite_op_setfield(op,
716 override_type=TYPE))
717 elif isinstance(TYPE, lltype.Array):
718 assert False # this operation disappeared
719 else:
720 raise TypeError("Expected struct or array, got '%r'", (TYPE,))
721 if len(ops) == 1:
722 return ops[0]
723 return ops
724
725 def extend_with(self, l, ops):
726 if ops is None:
727 return
728 if isinstance(ops, list):
729 l.extend(ops)
730 else:
731 l.append(ops)
732
733 def rewrite_op_free(self, op):
734 d = op.args[1].value.copy()
735 assert d['flavor'] == 'raw'
736 d.pop('flavor')
737 track_allocation = d.pop('track_allocation', True)
738 if d:
739 raise UnsupportedMallocFlags(d)
740 STRUCT = op.args[0].concretetype.TO
741 name = 'raw_free'
742 if not track_allocation:
743 name += '_no_track_allocation'
744 op1 = self.prepare_builtin_call(op, name, [op.args[0]], (STRUCT,),
745 STRUCT)
746 if name.startswith('raw_free'):
747 return self._handle_oopspec_call(op1, [op.args[0]],
748 EffectInfo.OS_RAW_FREE,
749 EffectInfo.EF_CANNOT_RAISE)
750 return self.rewrite_op_direct_call(op1)
751
752 def rewrite_op_getarrayitem(self, op):
753 ARRAY = op.args[0].concretetype.TO
754 if self._array_of_voids(ARRAY):
755 return []
756 if isinstance(ARRAY, lltype.FixedSizeArray):
757 raise NotImplementedError(
758 "%r uses %r, which is not supported by the JIT codewriter"
759 % (self.graph, ARRAY))
760 if op.args[0] in self.vable_array_vars: # for virtualizables
761 vars = self.vable_array_vars[op.args[0]]
762 (v_base, arrayfielddescr, arraydescr) = vars
763 kind = getkind(op.result.concretetype)
764 return [SpaceOperation('-live-', [], None),
765 SpaceOperation('getarrayitem_vable_%s' % kind[0],
766 [v_base, op.args[1], arrayfielddescr,
767 arraydescr], op.result)]
768 # normal case follows
769 pure = ''
770 immut = ARRAY._immutable_field(None)
771 if immut:
772 pure = '_pure'
773 arraydescr = self.cpu.arraydescrof(ARRAY)
774 kind = getkind(op.result.concretetype)
775 if ARRAY._gckind != 'gc':
776 assert ARRAY._gckind == 'raw'
777 if kind == 'r':
778 raise Exception("getarrayitem_raw_r not supported")
779 pure = '' # always redetected from pyjitpl.py: we don't need
780 # a '_pure' version of getarrayitem_raw
781 return SpaceOperation('getarrayitem_%s_%s%s' % (ARRAY._gckind,
782 kind[0], pure),
783 [op.args[0], op.args[1], arraydescr],
784 op.result)
785
786 def rewrite_op_setarrayitem(self, op):
787 ARRAY = op.args[0].concretetype.TO
788 if self._array_of_voids(ARRAY):
789 return []
790 if isinstance(ARRAY, lltype.FixedSizeArray):
791 raise NotImplementedError(
792 "%r uses %r, which is not supported by the JIT codewriter"
793 % (self.graph, ARRAY))
794 if op.args[0] in self.vable_array_vars: # for virtualizables
795 vars = self.vable_array_vars[op.args[0]]
796 (v_base, arrayfielddescr, arraydescr) = vars
797 kind = getkind(op.args[2].concretetype)
798 return [SpaceOperation('-live-', [], None),
799 SpaceOperation('setarrayitem_vable_%s' % kind[0],
800 [v_base, op.args[1], op.args[2],
801 arrayfielddescr, arraydescr], None)]
802 arraydescr = self.cpu.arraydescrof(ARRAY)
803 kind = getkind(op.args[2].concretetype)
804 return SpaceOperation('setarrayitem_%s_%s' % (ARRAY._gckind, kind[0]),
805 [op.args[0], op.args[1], op.args[2], arraydescr],
806 None)
807
808 def rewrite_op_getarraysize(self, op):
809 ARRAY = op.args[0].concretetype.TO
810 assert ARRAY._gckind == 'gc'
811 if op.args[0] in self.vable_array_vars: # for virtualizables
812 vars = self.vable_array_vars[op.args[0]]
813 (v_base, arrayfielddescr, arraydescr) = vars
814 return [SpaceOperation('-live-', [], None),
815 SpaceOperation('arraylen_vable',
816 [v_base, arrayfielddescr, arraydescr],
817 op.result)]
818 # normal case follows
819 arraydescr = self.cpu.arraydescrof(ARRAY)
820 return SpaceOperation('arraylen_gc', [op.args[0], arraydescr],
821 op.result)
822
823 def rewrite_op_getarraysubstruct(self, op):
824 ARRAY = op.args[0].concretetype.TO
825 assert ARRAY._gckind == 'raw'
826 assert ARRAY._hints.get('nolength') is True
827 return self.rewrite_op_direct_ptradd(op)
828
829 def _array_of_voids(self, ARRAY):
830 return ARRAY.OF == lltype.Void
831
832 def rewrite_op_getfield(self, op):
833 if self.is_typeptr_getset(op):
834 return self.handle_getfield_typeptr(op)
835 # turn the flow graph 'getfield' operation into our own version
836 [v_inst, c_fieldname] = op.args
837 RESULT = op.result.concretetype
838 if RESULT is lltype.Void:
839 return
840 # check for virtualizable
841 try:
842 if self.is_virtualizable_getset(op):
843 descr = self.get_virtualizable_field_descr(op)
844 kind = getkind(RESULT)[0]
845 return [SpaceOperation('-live-', [], None),
846 SpaceOperation('getfield_vable_%s' % kind,
847 [v_inst, descr], op.result)]
848 except VirtualizableArrayField as e:
849 # xxx hack hack hack
850 vinfo = e.args[1]
851 arrayindex = vinfo.array_field_counter[op.args[1].value]
852 arrayfielddescr = vinfo.array_field_descrs[arrayindex]
853 arraydescr = vinfo.array_descrs[arrayindex]
854 self.vable_array_vars[op.result] = (op.args[0],
855 arrayfielddescr,
856 arraydescr)
857 return []
858 # check for the string or unicode hash field
859 STRUCT = v_inst.concretetype.TO
860 if STRUCT == rstr.STR:
861 assert c_fieldname.value == 'hash'
862 return SpaceOperation('strhash', [v_inst], op.result)
863 elif STRUCT == rstr.UNICODE:
864 assert c_fieldname.value == 'hash'
865 return SpaceOperation('unicodehash', [v_inst], op.result)
866 # check for _immutable_fields_ hints
867 immut = STRUCT._immutable_field(c_fieldname.value)
868 need_live = False
869 if immut:
870 if (self.callcontrol is not None and
871 self.callcontrol.could_be_green_field(STRUCT,
872 c_fieldname.value)):
873 pure = '_greenfield'
874 need_live = True
875 else:
876 pure = '_pure'
877 else:
878 pure = ''
879 self.check_field_access(STRUCT)
880 argname = getattr(STRUCT, '_gckind', 'gc')
881 descr = self.cpu.fielddescrof(STRUCT, c_fieldname.value)
882 kind = getkind(RESULT)[0]
883 if argname != 'gc':
884 assert argname == 'raw'
885 if (kind, pure) == ('r', ''):
886 # note: a pure 'getfield_raw_r' is used e.g. to load class
887 # attributes that are GC objects, so that one is supported.
888 raise Exception("getfield_raw_r (without _pure) not supported")
889 pure = '' # always redetected from pyjitpl.py: we don't need
890 # a '_pure' version of getfield_raw
891 #
892 op1 = SpaceOperation('getfield_%s_%s%s' % (argname, kind, pure),
893 [v_inst, descr], op.result)
894 #
895 if immut in (IR_QUASIIMMUTABLE, IR_QUASIIMMUTABLE_ARRAY):
896 op1.opname += "_pure"
897 descr1 = self.cpu.fielddescrof(
898 STRUCT,
899 quasiimmut.get_mutate_field_name(c_fieldname.value))
900 return [SpaceOperation('-live-', [], None),
901 SpaceOperation('record_quasiimmut_field',
902 [v_inst, descr, descr1], None),
903 op1]
904 if need_live:
905 return [SpaceOperation('-live-', [], None), op1]
906 return op1
907
908 def rewrite_op_setfield(self, op, override_type=None):
909 if self.is_typeptr_getset(op):
910 # ignore the operation completely -- instead, it's done by 'new'
911 return
912 self._check_no_vable_array(op.args)
913 # turn the flow graph 'setfield' operation into our own version
914 [v_inst, c_fieldname, v_value] = op.args
915 RESULT = v_value.concretetype
916 if override_type is not None:
917 TYPE = override_type
918 else:
919 TYPE = v_inst.concretetype.TO
920 if RESULT is lltype.Void:
921 return
922 # check for virtualizable
923 if self.is_virtualizable_getset(op):
924 descr = self.get_virtualizable_field_descr(op)
925 kind = getkind(RESULT)[0]
926 return [SpaceOperation('-live-', [], None),
927 SpaceOperation('setfield_vable_%s' % kind,
928 [v_inst, v_value, descr], None)]
929 self.check_field_access(TYPE)
930 if override_type:
931 argname = 'gc'
932 else:
933 argname = getattr(TYPE, '_gckind', 'gc')
934 descr = self.cpu.fielddescrof(TYPE, c_fieldname.value)
935 kind = getkind(RESULT)[0]
936 if argname == 'raw' and kind == 'r':
937 raise Exception("setfield_raw_r not supported")
938 return SpaceOperation('setfield_%s_%s' % (argname, kind),
939 [v_inst, v_value, descr],
940 None)
941
942 def rewrite_op_getsubstruct(self, op):
943 STRUCT = op.args[0].concretetype.TO
944 argname = getattr(STRUCT, '_gckind', 'gc')
945 if argname != 'raw':
946 raise Exception("%r: only supported for gckind=raw" % (op,))
947 ofs = llmemory.offsetof(STRUCT, op.args[1].value)
948 return SpaceOperation('int_add',
949 [op.args[0], Constant(ofs, lltype.Signed)],
950 op.result)
951
952 def is_typeptr_getset(self, op):
953 return (op.args[1].value == 'typeptr' and
954 op.args[0].concretetype.TO._hints.get('typeptr'))
955
956 def check_field_access(self, STRUCT):
957 # check against a GcStruct with a nested GcStruct as a first argument
958 # but which is not an object at all; see metainterp/test/test_loop,
959 # test_regular_pointers_in_short_preamble.
960 if not isinstance(STRUCT, lltype.GcStruct):
961 return
962 if STRUCT._first_struct() == (None, None):
963 return
964 PARENT = STRUCT
965 while not PARENT._hints.get('typeptr'):
966 _, PARENT = PARENT._first_struct()
967 if PARENT is None:
968 raise NotImplementedError("%r is a GcStruct using nesting but "
969 "not inheriting from object" %
970 (STRUCT,))
971
972 def get_vinfo(self, v_virtualizable):
973 if self.callcontrol is None: # for tests
974 return None
975 return self.callcontrol.get_vinfo(v_virtualizable.concretetype)
976
977 def is_virtualizable_getset(self, op):
978 # every access of an object of exactly the type VTYPEPTR is
979 # likely to be a virtualizable access, but we still have to
980 # check it in pyjitpl.py.
981 vinfo = self.get_vinfo(op.args[0])
982 if vinfo is None:
983 return False
984 res = False
985 if op.args[1].value in vinfo.static_field_to_extra_box:
986 res = True
987 if op.args[1].value in vinfo.array_fields:
988 res = VirtualizableArrayField(self.graph, vinfo)
989
990 if res:
991 flags = self.vable_flags[op.args[0]]
992 if 'fresh_virtualizable' in flags:
993 return False
994 if isinstance(res, Exception):
995 raise res
996 return res
997
998 def get_virtualizable_field_descr(self, op):
999 fieldname = op.args[1].value
1000 vinfo = self.get_vinfo(op.args[0])
1001 index = vinfo.static_field_to_extra_box[fieldname]
1002 return vinfo.static_field_descrs[index]
1003
1004 def handle_getfield_typeptr(self, op):
1005 if isinstance(op.args[0], Constant):
1006 cls = op.args[0].value.typeptr
1007 return Constant(cls, concretetype=rclass.CLASSTYPE)
1008 op0 = SpaceOperation('-live-', [], None)
1009 op1 = SpaceOperation('guard_class', [op.args[0]], op.result)
1010 return [op0, op1]
1011
1012 def rewrite_op_malloc(self, op):
1013 d = op.args[1].value
1014 if d.get('nonmovable', False):
1015 raise UnsupportedMallocFlags(d)
1016 if d['flavor'] == 'raw':
1017 return self._rewrite_raw_malloc(op, 'raw_malloc_fixedsize', [])
1018 #
1019 if d.get('zero', False):
1020 zero = True
1021 else:
1022 zero = False
1023 STRUCT = op.args[0].value
1024 vtable = heaptracker.get_vtable_for_gcstruct(self.cpu, STRUCT)
1025 if vtable:
1026 # do we have a __del__?
1027 try:
1028 rtti = lltype.getRuntimeTypeInfo(STRUCT)
1029 except ValueError:
1030 pass
1031 else:
1032 if hasattr(rtti._obj, 'destructor_funcptr'):
1033 RESULT = lltype.Ptr(STRUCT)
1034 assert RESULT == op.result.concretetype
1035 return self._do_builtin_call(op, 'alloc_with_del', [],
1036 extra=(RESULT, vtable),
1037 extrakey=STRUCT)
1038 opname = 'new_with_vtable'
1039 else:
1040 opname = 'new'
1041 vtable = lltype.nullptr(rclass.OBJECT_VTABLE)
1042 sizedescr = self.cpu.sizeof(STRUCT, vtable)
1043 op1 = SpaceOperation(opname, [sizedescr], op.result)
1044 if zero:
1045 return self.zero_contents([op1], op.result, STRUCT)
1046 return op1
1047
1048 def _has_gcptrs_in(self, STRUCT):
1049 if isinstance(STRUCT, lltype.Array):
1050 ITEM = STRUCT.OF
1051 if isinstance(ITEM, lltype.Struct):
1052 STRUCT = ITEM
1053 else:
1054 return isinstance(ITEM, lltype.Ptr) and ITEM._needsgc()
1055 for FIELD in STRUCT._flds.values():
1056 if isinstance(FIELD, lltype.Ptr) and FIELD._needsgc():
1057 return True
1058 elif isinstance(FIELD, lltype.Struct):
1059 if self._has_gcptrs_in(FIELD):
1060 return True
1061 return False
1062
1063 def rewrite_op_getinteriorarraysize(self, op):
1064 # only supports strings and unicodes
1065 assert len(op.args) == 2
1066 assert op.args[1].value == 'chars'
1067 optype = op.args[0].concretetype
1068 if optype == lltype.Ptr(rstr.STR):
1069 opname = "strlen"
1070 elif optype == lltype.Ptr(rstr.UNICODE):
1071 opname = "unicodelen"
1072 elif optype == lltype.Ptr(rbytearray.BYTEARRAY):
1073 bytearraydescr = self.cpu.arraydescrof(rbytearray.BYTEARRAY)
1074 return SpaceOperation('arraylen_gc', [op.args[0], bytearraydescr],
1075 op.result)
1076 else:
1077 assert 0, "supported type %r" % (optype,)
1078 return SpaceOperation(opname, [op.args[0]], op.result)
1079
1080 def rewrite_op_getinteriorfield(self, op):
1081 assert len(op.args) == 3
1082 optype = op.args[0].concretetype
1083 if optype == lltype.Ptr(rstr.STR):
1084 opname = "strgetitem"
1085 return SpaceOperation(opname, [op.args[0], op.args[2]], op.result)
1086 elif optype == lltype.Ptr(rstr.UNICODE):
1087 opname = "unicodegetitem"
1088 return SpaceOperation(opname, [op.args[0], op.args[2]], op.result)
1089 elif optype == lltype.Ptr(rbytearray.BYTEARRAY):
1090 bytearraydescr = self.cpu.arraydescrof(rbytearray.BYTEARRAY)
1091 v_index = op.args[2]
1092 return SpaceOperation('getarrayitem_gc_i',
1093 [op.args[0], v_index, bytearraydescr],
1094 op.result)
1095 elif op.result.concretetype is lltype.Void:
1096 return
1097 elif isinstance(op.args[0].concretetype.TO, lltype.GcArray):
1098 # special-case 1: GcArray of Struct
1099 v_inst, v_index, c_field = op.args
1100 STRUCT = v_inst.concretetype.TO.OF
1101 assert isinstance(STRUCT, lltype.Struct)
1102 descr = self.cpu.interiorfielddescrof(v_inst.concretetype.TO,
1103 c_field.value)
1104 args = [v_inst, v_index, descr]
1105 kind = getkind(op.result.concretetype)[0]
1106 return SpaceOperation('getinteriorfield_gc_%s' % kind, args,
1107 op.result)
1108 #elif isinstance(op.args[0].concretetype.TO, lltype.GcStruct):
1109 # # special-case 2: GcStruct with Array field
1110 # ---was added in the faster-rstruct branch,---
1111 # ---no longer directly supported---
1112 # v_inst, c_field, v_index = op.args
1113 # STRUCT = v_inst.concretetype.TO
1114 # ARRAY = getattr(STRUCT, c_field.value)
1115 # assert isinstance(ARRAY, lltype.Array)
1116 # arraydescr = self.cpu.arraydescrof(STRUCT)
1117 # kind = getkind(op.result.concretetype)[0]
1118 # assert kind in ('i', 'f')
1119 # return SpaceOperation('getarrayitem_gc_%s' % kind,
1120 # [op.args[0], v_index, arraydescr],
1121 # op.result)
1122 else:
1123 assert False, 'not supported'
1124
1125 def rewrite_op_setinteriorfield(self, op):
1126 assert len(op.args) == 4
1127 optype = op.args[0].concretetype
1128 if optype == lltype.Ptr(rstr.STR):
1129 opname = "strsetitem"
1130 return SpaceOperation(opname, [op.args[0], op.args[2], op.args[3]],
1131 op.result)
1132 elif optype == lltype.Ptr(rstr.UNICODE):
1133 opname = "unicodesetitem"
1134 return SpaceOperation(opname, [op.args[0], op.args[2], op.args[3]],
1135 op.result)
1136 elif optype == lltype.Ptr(rbytearray.BYTEARRAY):
1137 bytearraydescr = self.cpu.arraydescrof(rbytearray.BYTEARRAY)
1138 opname = "setarrayitem_gc_i"
1139 return SpaceOperation(opname, [op.args[0], op.args[2], op.args[3],
1140 bytearraydescr], op.result)
1141 else:
1142 v_inst, v_index, c_field, v_value = op.args
1143 if v_value.concretetype is lltype.Void:
1144 return
1145 # only GcArray of Struct supported
1146 assert isinstance(v_inst.concretetype.TO, lltype.GcArray)
1147 STRUCT = v_inst.concretetype.TO.OF
1148 assert isinstance(STRUCT, lltype.Struct)
1149 descr = self.cpu.interiorfielddescrof(v_inst.concretetype.TO,
1150 c_field.value)
1151 kind = getkind(v_value.concretetype)[0]
1152 args = [v_inst, v_index, v_value, descr]
1153 return SpaceOperation('setinteriorfield_gc_%s' % kind, args,
1154 op.result)
1155
1156 def rewrite_op_raw_store(self, op):
1157 T = op.args[2].concretetype
1158 kind = getkind(T)[0]
1159 assert kind != 'r'
1160 descr = self.cpu.arraydescrof(rffi.CArray(T))
1161 return SpaceOperation('raw_store_%s' % kind,
1162 [op.args[0], op.args[1], op.args[2], descr],
1163 None)
1164
1165 def rewrite_op_raw_load(self, op):
1166 T = op.result.concretetype
1167 kind = getkind(T)[0]
1168 assert kind != 'r'
1169 descr = self.cpu.arraydescrof(rffi.CArray(T))
1170 return SpaceOperation('raw_load_%s' % kind,
1171 [op.args[0], op.args[1], descr], op.result)
1172
1173 def rewrite_op_gc_load_indexed(self, op):
1174 T = op.result.concretetype
1175 kind = getkind(T)[0]
1176 assert kind != 'r'
1177 descr = self.cpu.arraydescrof(rffi.CArray(T))
1178 if (not isinstance(op.args[2], Constant) or
1179 not isinstance(op.args[3], Constant)):
1180 raise NotImplementedError("gc_load_indexed: 'scale' and 'base_ofs'"
1181 " should be constants")
1182 # xxx hard-code the size in bytes at translation time, which is
1183 # probably fine and avoids lots of issues later
1184 bytes = descr.get_item_size_in_bytes()
1185 if descr.is_item_signed():
1186 bytes = -bytes
1187 c_bytes = Constant(bytes, lltype.Signed)
1188 return SpaceOperation('gc_load_indexed_%s' % kind,
1189 [op.args[0], op.args[1],
1190 op.args[2], op.args[3], c_bytes], op.result)
1191
1192 def rewrite_op_gc_store_indexed(self, op):
1193 T = op.args[2].concretetype
1194 kind = getkind(T)[0]
1195 assert kind != 'r'
1196 descr = self.cpu.arraydescrof(rffi.CArray(T))
1197 if (not isinstance(op.args[3], Constant) or
1198 not isinstance(op.args[4], Constant)):
1199 raise NotImplementedError("gc_store_indexed: 'scale' and 'base_ofs'"
1200 " should be constants")
1201 # According to the comment in resoperation.py, "itemsize is not signed
1202 # (always > 0)", so we don't need the "bytes = -bytes" line which is
1203 # in rewrite_op_gc_load_indexed
1204 bytes = descr.get_item_size_in_bytes()
1205 c_bytes = Constant(bytes, lltype.Signed)
1206 return SpaceOperation('gc_store_indexed_%s' % kind,
1207 [op.args[0], op.args[1], op.args[2],
1208 op.args[3], op.args[4], c_bytes, descr], None)
1209
1210
1211
1212 def _rewrite_equality(self, op, opname):
1213 arg0, arg1 = op.args
1214 if isinstance(arg0, Constant) and not arg0.value:
1215 return SpaceOperation(opname, [arg1], op.result)
1216 elif isinstance(arg1, Constant) and not arg1.value:
1217 return SpaceOperation(opname, [arg0], op.result)
1218 else:
1219 return self._rewrite_symmetric(op)
1220
1221 def _is_gc(self, v):
1222 return lltype_is_gc(v.concretetype)
1223
1224 def _is_rclass_instance(self, v):
1225 return lltype._castdepth(v.concretetype.TO, rclass.OBJECT) >= 0
1226
1227 def _rewrite_cmp_ptrs(self, op):
1228 if self._is_gc(op.args[0]):
1229 return op
1230 else:
1231 opname = {'ptr_eq': 'int_eq',
1232 'ptr_ne': 'int_ne',
1233 'ptr_iszero': 'int_is_zero',
1234 'ptr_nonzero': 'int_is_true'}[op.opname]
1235 return SpaceOperation(opname, op.args, op.result)
1236
1237 def rewrite_op_int_eq(self, op):
1238 return self._rewrite_equality(op, 'int_is_zero')
1239
1240 def rewrite_op_int_ne(self, op):
1241 return self._rewrite_equality(op, 'int_is_true')
1242
1243 def rewrite_op_ptr_eq(self, op):
1244 if self._is_rclass_instance(op.args[0]):
1245 assert self._is_rclass_instance(op.args[1])
1246 op = SpaceOperation('instance_ptr_eq', op.args, op.result)
1247 op1 = self._rewrite_equality(op, 'ptr_iszero')
1248 return self._rewrite_cmp_ptrs(op1)
1249
1250 def rewrite_op_ptr_ne(self, op):
1251 if self._is_rclass_instance(op.args[0]):
1252 assert self._is_rclass_instance(op.args[1])
1253 op = SpaceOperation('instance_ptr_ne', op.args, op.result)
1254 op1 = self._rewrite_equality(op, 'ptr_nonzero')
1255 return self._rewrite_cmp_ptrs(op1)
1256
1257 rewrite_op_ptr_iszero = _rewrite_cmp_ptrs
1258 rewrite_op_ptr_nonzero = _rewrite_cmp_ptrs
1259
1260 def rewrite_op_cast_ptr_to_int(self, op):
1261 if self._is_gc(op.args[0]):
1262 return op
1263
1264 def rewrite_op_cast_opaque_ptr(self, op):
1265 # None causes the result of this op to get aliased to op.args[0]
1266 return None
1267
1268 def rewrite_op_force_cast(self, op):
1269 v_arg = op.args[0]
1270 v_result = op.result
1271 if v_arg.concretetype == v_result.concretetype:
1272 return
1273 elif self._is_gc(v_arg) and self._is_gc(v_result):
1274 # cast from GC to GC is always fine
1275 return
1276 else:
1277 assert not self._is_gc(v_arg)
1278
1279 float_arg = v_arg.concretetype in [lltype.Float, lltype.SingleFloat]
1280 float_res = v_result.concretetype in [lltype.Float, lltype.SingleFloat]
1281 if not float_arg and not float_res:
1282 # some int -> some int cast
1283 return self._int_to_int_cast(v_arg, v_result)
1284 elif float_arg and float_res:
1285 # some float -> some float cast
1286 return self._float_to_float_cast(v_arg, v_result)
1287 elif not float_arg and float_res:
1288 # some int -> some float
1289 ops = []
1290 v2 = varoftype(lltype.Float)
1291 sizesign = rffi.size_and_sign(v_arg.concretetype)
1292 if sizesign <= rffi.size_and_sign(lltype.Signed):
1293 # cast from a type that fits in an int: either the size is
1294 # smaller, or it is equal and it is not unsigned
1295 v1 = varoftype(lltype.Signed)
1296 oplist = self.rewrite_operation(
1297 SpaceOperation('force_cast', [v_arg], v1)
1298 )
1299 if oplist:
1300 ops.extend(oplist)
1301 else:
1302 v1 = v_arg
1303 op = self.rewrite_operation(
1304 SpaceOperation('cast_int_to_float', [v1], v2)
1305 )
1306 ops.append(op)
1307 else:
1308 if sizesign == rffi.size_and_sign(lltype.Unsigned):
1309 opname = 'cast_uint_to_float'
1310 elif sizesign == rffi.size_and_sign(lltype.SignedLongLong):
1311 opname = 'cast_longlong_to_float'
1312 elif sizesign == rffi.size_and_sign(lltype.UnsignedLongLong):
1313 opname = 'cast_ulonglong_to_float'
1314 else:
1315 raise AssertionError('cast_x_to_float: %r' % (sizesign,))
1316 ops1 = self.rewrite_operation(
1317 SpaceOperation(opname, [v_arg], v2)
1318 )
1319 if not isinstance(ops1, list): ops1 = [ops1]
1320 ops.extend(ops1)
1321 op2 = self.rewrite_operation(
1322 SpaceOperation('force_cast', [v2], v_result)
1323 )
1324 if op2:
1325 ops.append(op2)
1326 else:
1327 ops[-1].result = v_result
1328 return ops
1329 elif float_arg and not float_res:
1330 # some float -> some int
1331 ops = []
1332 v1 = varoftype(lltype.Float)
1333 op1 = self.rewrite_operation(
1334 SpaceOperation('force_cast', [v_arg], v1)
1335 )
1336 if op1:
1337 ops.append(op1)
1338 else:
1339 v1 = v_arg
1340 sizesign = rffi.size_and_sign(v_result.concretetype)
1341 if v_result.concretetype is lltype.Bool:
1342 op = self.rewrite_operation(
1343 SpaceOperation('float_is_true', [v1], v_result)
1344 )
1345 ops.append(op)
1346 elif sizesign <= rffi.size_and_sign(lltype.Signed):
1347 # cast to a type that fits in an int: either the size is
1348 # smaller, or it is equal and it is not unsigned
1349 v2 = varoftype(lltype.Signed)
1350 op = self.rewrite_operation(
1351 SpaceOperation('cast_float_to_int', [v1], v2)
1352 )
1353 ops.append(op)
1354 oplist = self.rewrite_operation(
1355 SpaceOperation('force_cast', [v2], v_result)
1356 )
1357 if oplist:
1358 ops.extend(oplist)
1359 else:
1360 op.result = v_result
1361 else:
1362 if sizesign == rffi.size_and_sign(lltype.Unsigned):
1363 opname = 'cast_float_to_uint'
1364 elif sizesign == rffi.size_and_sign(lltype.SignedLongLong):
1365 opname = 'cast_float_to_longlong'
1366 elif sizesign == rffi.size_and_sign(lltype.UnsignedLongLong):
1367 opname = 'cast_float_to_ulonglong'
1368 else:
1369 raise AssertionError('cast_float_to_x: %r' % (sizesign,))
1370 ops1 = self.rewrite_operation(
1371 SpaceOperation(opname, [v1], v_result)
1372 )
1373 if not isinstance(ops1, list): ops1 = [ops1]
1374 ops.extend(ops1)
1375 return ops
1376 else:
1377 assert False
1378
1379 def _int_to_int_cast(self, v_arg, v_result):
1380 longlong_arg = longlong.is_longlong(v_arg.concretetype)
1381 longlong_res = longlong.is_longlong(v_result.concretetype)
1382 size1, unsigned1 = rffi.size_and_sign(v_arg.concretetype)
1383 size2, unsigned2 = rffi.size_and_sign(v_result.concretetype)
1384
1385 if longlong_arg and longlong_res:
1386 return
1387 elif longlong_arg:
1388 if v_result.concretetype is lltype.Bool:
1389 longlong_zero = rffi.cast(v_arg.concretetype, 0)
1390 c_longlong_zero = Constant(longlong_zero, v_arg.concretetype)
1391 if unsigned1:
1392 name = 'ullong_ne'
1393 else:
1394 name = 'llong_ne'
1395 op1 = SpaceOperation(name, [v_arg, c_longlong_zero], v_result)
1396 return self.rewrite_operation(op1)
1397 v = varoftype(lltype.Signed)
1398 op1 = self.rewrite_operation(
1399 SpaceOperation('truncate_longlong_to_int', [v_arg], v)
1400 )
1401 op2 = SpaceOperation('force_cast', [v], v_result)
1402 oplist = self.rewrite_operation(op2)
1403 if not oplist:
1404 op1.result = v_result
1405 oplist = []
1406 return [op1] + oplist
1407 elif longlong_res:
1408 if unsigned1:
1409 INTERMEDIATE = lltype.Unsigned
1410 else:
1411 INTERMEDIATE = lltype.Signed
1412 v = varoftype(INTERMEDIATE)
1413 op1 = SpaceOperation('force_cast', [v_arg], v)
1414 oplist = self.rewrite_operation(op1)
1415 if not oplist:
1416 v = v_arg
1417 oplist = []
1418 if unsigned1:
1419 if unsigned2:
1420 opname = 'cast_uint_to_ulonglong'
1421 else:
1422 opname = 'cast_uint_to_longlong'
1423 else:
1424 if unsigned2:
1425 opname = 'cast_int_to_ulonglong'
1426 else:
1427 opname = 'cast_int_to_longlong'
1428 op2 = self.rewrite_operation(
1429 SpaceOperation(opname, [v], v_result)
1430 )
1431 return oplist + [op2]
1432
1433 # We've now, ostensibly, dealt with the longlongs, everything should be
1434 # a Signed or smaller
1435 assert size1 <= rffi.sizeof(lltype.Signed)
1436 assert size2 <= rffi.sizeof(lltype.Signed)
1437
1438 # the target type is LONG or ULONG
1439 if size2 == rffi.sizeof(lltype.Signed):
1440 return
1441
1442 min1, max1 = integer_bounds(size1, unsigned1)
1443 min2, max2 = integer_bounds(size2, unsigned2)
1444
1445 # the target type includes the source range
1446 if min2 <= min1 <= max1 <= max2:
1447 return
1448
1449 result = []
1450 if v_result.concretetype is lltype.Bool:
1451 result.append(SpaceOperation('int_is_true', [v_arg], v_result))
1452 elif min2:
1453 c_bytes = Constant(size2, lltype.Signed)
1454 result.append(SpaceOperation('int_signext', [v_arg, c_bytes],
1455 v_result))
1456 else:
1457 c_mask = Constant(int((1 << (8 * size2)) - 1), lltype.Signed)
1458 result.append(SpaceOperation('int_and', [v_arg, c_mask], v_result))
1459 return result
1460
1461 def _float_to_float_cast(self, v_arg, v_result):
1462 if v_arg.concretetype == lltype.SingleFloat:
1463 assert v_result.concretetype == lltype.Float, "cast %s -> %s" % (
1464 v_arg.concretetype, v_result.concretetype)
1465 return SpaceOperation('cast_singlefloat_to_float', [v_arg],
1466 v_result)
1467 if v_result.concretetype == lltype.SingleFloat:
1468 assert v_arg.concretetype == lltype.Float, "cast %s -> %s" % (
1469 v_arg.concretetype, v_result.concretetype)
1470 return SpaceOperation('cast_float_to_singlefloat', [v_arg],
1471 v_result)
1472
1473 def rewrite_op_direct_ptradd(self, op):
1474 v_shift = op.args[1]
1475 assert v_shift.concretetype == lltype.Signed
1476 ops = []
1477 #
1478 if op.args[0].concretetype != rffi.CCHARP:
1479 v_prod = varoftype(lltype.Signed)
1480 by = llmemory.sizeof(op.args[0].concretetype.TO.OF)
1481 c_by = Constant(by, lltype.Signed)
1482 ops.append(SpaceOperation('int_mul', [v_shift, c_by], v_prod))
1483 v_shift = v_prod
1484 #
1485 ops.append(SpaceOperation('int_add', [op.args[0], v_shift], op.result))
1486 return ops
1487
1488 # ----------
1489 # Long longs, for 32-bit only. Supported operations are left unmodified,
1490 # and unsupported ones are turned into a call to a function from
1491 # jit.codewriter.support.
1492
1493 for _op, _oopspec in [('llong_invert', 'INVERT'),
1494 ('llong_lt', 'LT'),
1495 ('llong_le', 'LE'),
1496 ('llong_eq', 'EQ'),
1497 ('llong_ne', 'NE'),
1498 ('llong_gt', 'GT'),
1499 ('llong_ge', 'GE'),
1500 ('llong_add', 'ADD'),
1501 ('llong_sub', 'SUB'),
1502 ('llong_mul', 'MUL'),
1503 ('llong_and', 'AND'),
1504 ('llong_or', 'OR'),
1505 ('llong_xor', 'XOR'),
1506 ('llong_lshift', 'LSHIFT'),
1507 ('llong_rshift', 'RSHIFT'),
1508 ('cast_int_to_longlong', 'FROM_INT'),
1509 ('truncate_longlong_to_int', 'TO_INT'),
1510 ('cast_float_to_longlong', 'FROM_FLOAT'),
1511 ('cast_longlong_to_float', 'TO_FLOAT'),
1512 ('cast_uint_to_longlong', 'FROM_UINT'),
1513 ]:
1514 exec(py.code.Source('''
1515 def rewrite_op_%s(self, op):
1516 args = op.args
1517 op1 = self.prepare_builtin_call(op, "llong_%s", args)
1518 op2 = self._handle_oopspec_call(op1, args,
1519 EffectInfo.OS_LLONG_%s,
1520 EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
1521 if %r == "TO_INT":
1522 assert op2.result.concretetype == lltype.Signed
1523 return op2
1524 ''' % (_op, _oopspec.lower(), _oopspec, _oopspec)).compile())
1525
1526 for _op, _oopspec in [('cast_int_to_ulonglong', 'FROM_INT'),
1527 ('cast_uint_to_ulonglong', 'FROM_UINT'),
1528 ('cast_float_to_ulonglong', 'FROM_FLOAT'),
1529 ('cast_ulonglong_to_float', 'U_TO_FLOAT'),
1530 ('ullong_invert', 'INVERT'),
1531 ('ullong_lt', 'ULT'),
1532 ('ullong_le', 'ULE'),
1533 ('ullong_eq', 'EQ'),
1534 ('ullong_ne', 'NE'),
1535 ('ullong_gt', 'UGT'),
1536 ('ullong_ge', 'UGE'),
1537 ('ullong_add', 'ADD'),
1538 ('ullong_sub', 'SUB'),
1539 ('ullong_mul', 'MUL'),
1540 ('ullong_and', 'AND'),
1541 ('ullong_or', 'OR'),
1542 ('ullong_xor', 'XOR'),
1543 ('ullong_lshift', 'LSHIFT'),
1544 ('ullong_rshift', 'URSHIFT'),
1545 ]:
1546 exec(py.code.Source('''
1547 def rewrite_op_%s(self, op):
1548 args = op.args
1549 op1 = self.prepare_builtin_call(op, "ullong_%s", args)
1550 op2 = self._handle_oopspec_call(op1, args,
1551 EffectInfo.OS_LLONG_%s,
1552 EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
1553 return op2
1554 ''' % (_op, _oopspec.lower(), _oopspec)).compile())
1555
1556 def _normalize(self, oplist):
1557 if isinstance(oplist, SpaceOperation):
1558 return [oplist]
1559 else:
1560 assert type(oplist) is list
1561 return oplist
1562
1563 def rewrite_op_llong_neg(self, op):
1564 v = varoftype(lltype.SignedLongLong)
1565 op0 = SpaceOperation('cast_int_to_longlong',
1566 [Constant(0, lltype.Signed)],
1567 v)
1568 args = [v, op.args[0]]
1569 op1 = SpaceOperation('llong_sub', args, op.result)
1570 return (self._normalize(self.rewrite_operation(op0)) +
1571 self._normalize(self.rewrite_operation(op1)))
1572
1573 def rewrite_op_llong_is_true(self, op):
1574 v = varoftype(op.args[0].concretetype)
1575 op0 = SpaceOperation('cast_primitive',
1576 [Constant(0, lltype.Signed)],
1577 v)
1578 args = [op.args[0], v]
1579 op1 = SpaceOperation('llong_ne', args, op.result)
1580 return (self._normalize(self.rewrite_operation(op0)) +
1581 self._normalize(self.rewrite_operation(op1)))
1582
1583 rewrite_op_ullong_is_true = rewrite_op_llong_is_true
1584
1585 def rewrite_op_cast_primitive(self, op):
1586 return self.rewrite_op_force_cast(op)
1587
1588 # ----------
1589 # Renames, from the _old opname to the _new one.
1590 # The new operation is optionally further processed by rewrite_operation().
1591 for _old, _new in [('bool_not', 'int_is_zero'),
1592 ('cast_bool_to_float', 'cast_int_to_float'),
1593
1594 ('int_add_nonneg_ovf', 'int_add_ovf'),
1595 ('keepalive', '-live-'),
1596
1597 ('char_lt', 'int_lt'),
1598 ('char_le', 'int_le'),
1599 ('char_eq', 'int_eq'),
1600 ('char_ne', 'int_ne'),
1601 ('char_gt', 'int_gt'),
1602 ('char_ge', 'int_ge'),
1603 ('unichar_eq', 'int_eq'),
1604 ('unichar_ne', 'int_ne'),
1605
1606 ('uint_is_true', 'int_is_true'),
1607 ('uint_invert', 'int_invert'),
1608 ('uint_add', 'int_add'),
1609 ('uint_sub', 'int_sub'),
1610 ('uint_mul', 'int_mul'),
1611 ('uint_eq', 'int_eq'),
1612 ('uint_ne', 'int_ne'),
1613 ('uint_and', 'int_and'),
1614 ('uint_or', 'int_or'),
1615 ('uint_lshift', 'int_lshift'),
1616 ('uint_xor', 'int_xor'),
1617
1618 ('adr_add', 'int_add'),
1619 ]:
1620 assert _old not in locals()
1621 exec(py.code.Source('''
1622 def rewrite_op_%s(self, op):
1623 op1 = SpaceOperation(%r, op.args, op.result)
1624 return self.rewrite_operation(op1)
1625 ''' % (_old, _new)).compile())
1626
1627 def rewrite_op_float_is_true(self, op):
1628 op1 = SpaceOperation('float_ne',
1629 [op.args[0], Constant(0.0, lltype.Float)],
1630 op.result)
1631 return self.rewrite_operation(op1)
1632
1633 def rewrite_op_int_is_true(self, op):
1634 if isinstance(op.args[0], Constant):
1635 value = op.args[0].value
1636 if value is objectmodel.malloc_zero_filled:
1637 value = True
1638 elif value is _we_are_jitted:
1639 value = True
1640 else:
1641 raise AssertionError("don't know the truth value of %r"
1642 % (value,))
1643 return Constant(value, lltype.Bool)
1644 return op
1645
1646 def promote_greens(self, args, jitdriver):
1647 ops = []
1648 num_green_args = len(jitdriver.greens)
1649 assert len(args) == num_green_args + jitdriver.numreds
1650 for v in args[:num_green_args]:
1651 if isinstance(v, Variable) and v.concretetype is not lltype.Void:
1652 kind = getkind(v.concretetype)
1653 ops.append(SpaceOperation('-live-', [], None))
1654 ops.append(SpaceOperation('%s_guard_value' % kind,
1655 [v], None))
1656 return ops
1657
1658 def rewrite_op_jit_marker(self, op):
1659 key = op.args[0].value
1660 jitdriver = op.args[1].value
1661 if not jitdriver.active:
1662 return []
1663 return getattr(self, 'handle_jit_marker__%s' % key)(op, jitdriver)
1664
1665 def _rewrite_op_cond_call(self, op, rewritten_opname):
1666 have_floats = False
1667 for arg in op.args:
1668 if getkind(arg.concretetype) == 'float':
1669 have_floats = True
1670 break
1671 if len(op.args) > 4 + 2 or have_floats:
1672 raise Exception("Conditional call does not support floats or more than 4 arguments")
1673 callop = SpaceOperation('direct_call', op.args[1:], op.result)
1674 calldescr = self.callcontrol.getcalldescr(
1675 callop,
1676 calling_graph=self.graph)
1677 assert not calldescr.get_extra_info().check_forces_virtual_or_virtualizable()
1678 op1 = self.rewrite_call(op, rewritten_opname,
1679 op.args[:2], args=op.args[2:],
1680 calldescr=calldescr, force_ir=True)
1681 if self.callcontrol.calldescr_canraise(calldescr):
1682 op1 = [op1, SpaceOperation('-live-', [], None)]
1683 return op1
1684
1685 def rewrite_op_jit_conditional_call(self, op):
1686 return self._rewrite_op_cond_call(op, 'conditional_call')
1687 def rewrite_op_jit_conditional_call_value(self, op):
1688 return self._rewrite_op_cond_call(op, 'conditional_call_value')
1689
1690 def handle_jit_marker__jit_merge_point(self, op, jitdriver):
1691 assert self.portal_jd is not None, (
1692 "'jit_merge_point' in non-portal graph!")
1693 assert jitdriver is self.portal_jd.jitdriver, (
1694 "general mix-up of jitdrivers?")
1695 ops = self.promote_greens(op.args[2:], jitdriver)
1696 num_green_args = len(jitdriver.greens)
1697 redlists = self.make_three_lists(op.args[2+num_green_args:])
1698 for redlist in redlists:
1699 for v in redlist:
1700 assert isinstance(v, Variable), (
1701 "Constant specified red in jit_merge_point()")
1702 assert len(dict.fromkeys(redlist)) == len(list(redlist)), (
1703 "duplicate red variable on jit_merge_point()")
1704 args = ([Constant(self.portal_jd.index, lltype.Signed)] +
1705 self.make_three_lists(op.args[2:2+num_green_args]) +
1706 redlists)
1707 op1 = SpaceOperation('jit_merge_point', args, None)
1708 op2 = SpaceOperation('-live-', [], None)
1709 # ^^^ we need a -live- for the case of do_recursive_call()
1710 op3 = SpaceOperation('-live-', [], None)
1711 # and one for inlined short preambles
1712 return ops + [op3, op1, op2]
1713
1714 def handle_jit_marker__loop_header(self, op, jitdriver):
1715 jd = self.callcontrol.jitdriver_sd_from_jitdriver(jitdriver)
1716 assert jd is not None
1717 c_index = Constant(jd.index, lltype.Signed)
1718 return SpaceOperation('loop_header', [c_index], None)
1719
1720 # a 'can_enter_jit' in the source graph becomes a 'loop_header'
1721 # operation in the transformed graph, as its only purpose in
1722 # the transformed graph is to detect loops.
1723 handle_jit_marker__can_enter_jit = handle_jit_marker__loop_header
1724
1725 def rewrite_op_debug_assert(self, op):
1726 log.WARNING("found debug_assert in %r; should have be removed" %
1727 (self.graph,))
1728 return []
1729
1730 def _handle_jit_call(self, op, oopspec_name, args):
1731 if oopspec_name == 'jit.debug':
1732 return SpaceOperation('jit_debug', args, None)
1733 elif oopspec_name == 'jit.assert_green':
1734 kind = getkind(args[0].concretetype)
1735 return SpaceOperation('%s_assert_green' % kind, args, None)
1736 elif oopspec_name == 'jit.current_trace_length':
1737 return SpaceOperation('current_trace_length', [], op.result)
1738 elif oopspec_name == 'jit.isconstant':
1739 kind = getkind(args[0].concretetype)
1740 return SpaceOperation('%s_isconstant' % kind, args, op.result)
1741 elif oopspec_name == 'jit.isvirtual':
1742 kind = getkind(args[0].concretetype)
1743 return SpaceOperation('%s_isvirtual' % kind, args, op.result)
1744 elif oopspec_name == 'jit.force_virtual':
1745 return self._handle_oopspec_call(op, args,
1746 EffectInfo.OS_JIT_FORCE_VIRTUAL,
1747 EffectInfo.EF_FORCES_VIRTUAL_OR_VIRTUALIZABLE)
1748 elif oopspec_name == 'jit.not_in_trace':
1749 # ignore 'args' and use the original 'op.args'
1750 if op.result.concretetype is not lltype.Void:
1751 raise Exception(
1752 "%r: jit.not_in_trace() function must return None"
1753 % (op.args[0],))
1754 return self._handle_oopspec_call(op, op.args[1:],
1755 EffectInfo.OS_NOT_IN_TRACE)
1756 else:
1757 raise AssertionError("missing support for %r" % oopspec_name)
1758
1759 # ----------
1760 # Lists.
1761
1762 def _handle_list_call(self, op, oopspec_name, args):
1763 """Try to transform the call to a list-handling helper.
1764 If no transformation is available, raise NotSupported
1765 (in which case the original call is written as a residual call).
1766 """
1767 if oopspec_name.startswith('new'):
1768 LIST = op.result.concretetype.TO
1769 else:
1770 LIST = args[0].concretetype.TO
1771 resizable = isinstance(LIST, lltype.GcStruct)
1772 assert resizable == (not isinstance(LIST, lltype.GcArray))
1773 if resizable:
1774 prefix = 'do_resizable_'
1775 ARRAY = LIST.items.TO
1776 if self._array_of_voids(ARRAY):
1777 prefix += 'void_'
1778 descrs = ()
1779 else:
1780 descrs = (self.cpu.arraydescrof(ARRAY),
1781 self.cpu.fielddescrof(LIST, 'length'),
1782 self.cpu.fielddescrof(LIST, 'items'),
1783 self.cpu.sizeof(LIST, None))
1784 else:
1785 prefix = 'do_fixed_'
1786 if self._array_of_voids(LIST):
1787 prefix += 'void_'
1788 descrs = ()
1789 else:
1790 arraydescr = self.cpu.arraydescrof(LIST)
1791 descrs = (arraydescr,)
1792 #
1793 try:
1794 meth = getattr(self, prefix + oopspec_name.replace('.', '_'))
1795 except AttributeError:
1796 raise NotSupported(prefix + oopspec_name)
1797 return meth(op, args, *descrs)
1798
1799 def _get_list_nonneg_canraise_flags(self, op):
1800 # XXX as far as I can see, this function will always return True
1801 # because functions that are neither nonneg nor fast don't have an
1802 # oopspec any more
1803 # xxx break of abstraction:
1804 func = op.args[0].value._obj._callable
1805 # base hints on the name of the ll function, which is a bit xxx-ish
1806 # but which is safe for now
1807 assert func.__name__.startswith('ll_')
1808 # check that we have carefully placed the oopspec in
1809 # pypy/rpython/rlist.py. There should not be an oopspec on
1810 # a ll_getitem or ll_setitem that expects a 'func' argument.
1811 # The idea is that a ll_getitem/ll_setitem with dum_checkidx
1812 # should get inlined by the JIT, so that we see the potential
1813 # 'raise IndexError'.
1814 assert 'func' not in func.__code__.co_varnames
1815 non_negative = '_nonneg' in func.__name__
1816 fast = '_fast' in func.__name__
1817 return non_negative or fast
1818
1819 def _prepare_list_getset(self, op, descr, args, checkname):
1820 non_negative = self._get_list_nonneg_canraise_flags(op)
1821 if non_negative:
1822 return args[1], []
1823 else:
1824 v_posindex = Variable('posindex')
1825 v_posindex.concretetype = lltype.Signed
1826 op0 = SpaceOperation('-live-', [], None)
1827 op1 = SpaceOperation(checkname, [args[0], args[1],
1828 descr], v_posindex)
1829 return v_posindex, [op0, op1]
1830
1831 def _prepare_void_list_getset(self, op):
1832 # sanity check:
1833 self._get_list_nonneg_canraise_flags(op)
1834
1835 def _get_initial_newlist_length(self, op, args):
1836 assert len(args) <= 1
1837 if len(args) == 1:
1838 v_length = args[0]
1839 assert v_length.concretetype is lltype.Signed
1840 return v_length
1841 else:
1842 return Constant(0, lltype.Signed) # length: default to 0
1843
1844 # ---------- fixed lists ----------
1845
1846 def do_fixed_newlist(self, op, args, arraydescr):
1847 # corresponds to rtyper.lltypesystem.rlist.newlist:
1848 # the items may be uninitialized.
1849 v_length = self._get_initial_newlist_length(op, args)
1850 ARRAY = op.result.concretetype.TO
1851 if ((isinstance(ARRAY.OF, lltype.Ptr) and ARRAY.OF._needsgc()) or
1852 isinstance(ARRAY.OF, lltype.Struct)):
1853 opname = 'new_array_clear'
1854 else:
1855 opname = 'new_array'
1856 return SpaceOperation(opname, [v_length, arraydescr], op.result)
1857
1858 def do_fixed_newlist_clear(self, op, args, arraydescr):
1859 # corresponds to rtyper.rlist.ll_alloc_and_clear:
1860 # needs to clear the items.
1861 v_length = self._get_initial_newlist_length(op, args)
1862 return SpaceOperation('new_array_clear', [v_length, arraydescr],
1863 op.result)
1864
1865 def do_fixed_list_len(self, op, args, arraydescr):
1866 if args[0] in self.vable_array_vars: # virtualizable array
1867 vars = self.vable_array_vars[args[0]]
1868 (v_base, arrayfielddescr, arraydescr) = vars
1869 return [SpaceOperation('-live-', [], None),
1870 SpaceOperation('arraylen_vable',
1871 [v_base, arrayfielddescr, arraydescr],
1872 op.result)]
1873 return SpaceOperation('arraylen_gc', [args[0], arraydescr], op.result)
1874
1875 do_fixed_list_len_foldable = do_fixed_list_len
1876
1877 def do_fixed_list_getitem(self, op, args, arraydescr, pure=False):
1878 if args[0] in self.vable_array_vars: # virtualizable array
1879 vars = self.vable_array_vars[args[0]]
1880 (v_base, arrayfielddescr, arraydescr) = vars
1881 kind = getkind(op.result.concretetype)
1882 return [SpaceOperation('-live-', [], None),
1883 SpaceOperation('getarrayitem_vable_%s' % kind[0],
1884 [v_base, args[1], arrayfielddescr,
1885 arraydescr], op.result)]
1886 v_index, extraop = self._prepare_list_getset(op, arraydescr, args,
1887 'check_neg_index')
1888 extra = getkind(op.result.concretetype)[0]
1889 if pure:
1890 extra += '_pure'
1891 op = SpaceOperation('getarrayitem_gc_%s' % extra,
1892 [args[0], v_index, arraydescr], op.result)
1893 return extraop + [op]
1894
1895 def do_fixed_list_getitem_foldable(self, op, args, arraydescr):
1896 return self.do_fixed_list_getitem(op, args, arraydescr, pure=True)
1897
1898 def do_fixed_list_setitem(self, op, args, arraydescr):
1899 if args[0] in self.vable_array_vars: # virtualizable array
1900 vars = self.vable_array_vars[args[0]]
1901 (v_base, arrayfielddescr, arraydescr) = vars
1902 kind = getkind(args[2].concretetype)
1903 return [SpaceOperation('-live-', [], None),
1904 SpaceOperation('setarrayitem_vable_%s' % kind[0],
1905 [v_base, args[1], args[2],
1906 arrayfielddescr, arraydescr], None)]
1907 v_index, extraop = self._prepare_list_getset(op, arraydescr, args,
1908 'check_neg_index')
1909 kind = getkind(args[2].concretetype)[0]
1910 op = SpaceOperation('setarrayitem_gc_%s' % kind,
1911 [args[0], v_index, args[2], arraydescr], None)
1912 return extraop + [op]
1913
1914 def do_fixed_list_ll_arraycopy(self, op, args, arraydescr):
1915 return self._handle_oopspec_call(op, args, EffectInfo.OS_ARRAYCOPY)
1916
1917 def do_fixed_list_ll_arraymove(self, op, args, arraydescr):
1918 # this case is unreachable for now: ll_arraymove is only called on
1919 # lists which have insert() or pop() or del called on them
1920 return self._handle_oopspec_call(op, args, EffectInfo.OS_ARRAYMOVE)
1921
1922 def do_fixed_void_list_getitem(self, op, args):
1923 self._prepare_void_list_getset(op)
1924 return []
1925 do_fixed_void_list_getitem_foldable = do_fixed_void_list_getitem
1926 do_fixed_void_list_setitem = do_fixed_void_list_getitem
1927
1928 # ---------- resizable lists ----------
1929
1930 def do_resizable_newlist(self, op, args, arraydescr, lengthdescr,
1931 itemsdescr, structdescr):
1932 v_length = self._get_initial_newlist_length(op, args)
1933 return SpaceOperation('newlist',
1934 [v_length, structdescr, lengthdescr, itemsdescr,
1935 arraydescr],
1936 op.result)
1937
1938 def do_resizable_newlist_clear(self, op, args, arraydescr, lengthdescr,
1939 itemsdescr, structdescr):
1940 v_length = self._get_initial_newlist_length(op, args)
1941 return SpaceOperation('newlist_clear',
1942 [v_length, structdescr, lengthdescr, itemsdescr,
1943 arraydescr],
1944 op.result)
1945
1946 def do_resizable_newlist_hint(self, op, args, arraydescr, lengthdescr,
1947 itemsdescr, structdescr):
1948 v_hint = self._get_initial_newlist_length(op, args)
1949 return SpaceOperation('newlist_hint',
1950 [v_hint, structdescr, lengthdescr, itemsdescr,
1951 arraydescr],
1952 op.result)
1953
1954 def do_resizable_list_getitem(self, op, args, arraydescr, lengthdescr,
1955 itemsdescr, structdescr):
1956 v_index, extraop = self._prepare_list_getset(op, lengthdescr, args,
1957 'check_resizable_neg_index')
1958 kind = getkind(op.result.concretetype)[0]
1959 op = SpaceOperation('getlistitem_gc_%s' % kind,
1960 [args[0], v_index, itemsdescr, arraydescr],
1961 op.result)
1962 return extraop + [op]
1963
1964 def do_resizable_list_setitem(self, op, args, arraydescr, lengthdescr,
1965 itemsdescr, structdescr):
1966 v_index, extraop = self._prepare_list_getset(op, lengthdescr, args,
1967 'check_resizable_neg_index')
1968 kind = getkind(args[2].concretetype)[0]
1969 op = SpaceOperation('setlistitem_gc_%s' % kind,
1970 [args[0], v_index, args[2],
1971 itemsdescr, arraydescr], None)
1972 return extraop + [op]
1973
1974 def do_resizable_list_len(self, op, args, arraydescr, lengthdescr,
1975 itemsdescr, structdescr):
1976 return SpaceOperation('getfield_gc_i',
1977 [args[0], lengthdescr], op.result)
1978
1979 def do_resizable_void_list_getitem(self, op, args):
1980 self._prepare_void_list_getset(op)
1981 return []
1982 do_resizable_void_list_getitem_foldable = do_resizable_void_list_getitem
1983 do_resizable_void_list_setitem = do_resizable_void_list_getitem
1984
1985 # ----------
1986 # Strings and Unicodes.
1987
1988 def _handle_oopspec_call(self, op, args, oopspecindex, extraeffect=None,
1989 extradescr=None):
1990 calldescr = self.callcontrol.getcalldescr(op, oopspecindex,
1991 extraeffect,
1992 extradescr=extradescr,
1993 calling_graph=self.graph)
1994 if extraeffect is not None:
1995 assert (is_test_calldescr(calldescr) # for tests
1996 or calldescr.get_extra_info().extraeffect == extraeffect)
1997 if isinstance(op.args[0].value, str):
1998 pass # for tests only
1999 else:
2000 func = ptr2int(op.args[0].value)
2001 self.callcontrol.callinfocollection.add(oopspecindex,
2002 calldescr, func)
2003 op1 = self.rewrite_call(op, 'residual_call',
2004 [op.args[0]],
2005 args=args, calldescr=calldescr)
2006 if self.callcontrol.calldescr_canraise(calldescr):
2007 op1 = [op1, SpaceOperation('-live-', [], None)]
2008 return op1
2009
2010 def _register_extra_helper(self, oopspecindex, oopspec_name,
2011 argtypes, resulttype, effectinfo):
2012 # a bit hackish
2013 if self.callcontrol.callinfocollection.has_oopspec(oopspecindex):
2014 return
2015 c_func, TP = support.builtin_func_for_spec(self.cpu.rtyper,
2016 oopspec_name, argtypes,
2017 resulttype)
2018 op = SpaceOperation('pseudo_call_cannot_raise',
2019 [c_func] + [varoftype(T) for T in argtypes],
2020 varoftype(resulttype))
2021 calldescr = self.callcontrol.getcalldescr(op, oopspecindex,
2022 effectinfo,
2023 calling_graph=self.graph)
2024 if isinstance(c_func.value, str): # in tests only
2025 func = c_func.value
2026 else:
2027 func = ptr2int(c_func.value)
2028 self.callcontrol.callinfocollection.add(oopspecindex, calldescr, func)
2029
2030 def _handle_int_special(self, op, oopspec_name, args):
2031 if oopspec_name == 'int.neg_ovf':
2032 [v_x] = args
2033 op0 = SpaceOperation('int_sub_ovf',
2034 [Constant(0, lltype.Signed), v_x],
2035 op.result)
2036 return self.rewrite_operation(op0)
2037 elif oopspec_name == 'int.uint_mul_high':
2038 op0 = SpaceOperation('uint_mul_high',
2039 args,
2040 op.result)
2041 return self.rewrite_operation(op0)
2042 else:
2043 # int.py_div, int.udiv, int.py_mod, int.umod
2044 opname = oopspec_name.replace('.', '_')
2045 os = getattr(EffectInfo, 'OS_' + opname.upper())
2046 return self._handle_oopspec_call(op, args, os,
2047 EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
2048
2049 def _handle_stroruni_call(self, op, oopspec_name, args):
2050 SoU = args[0].concretetype # Ptr(STR) or Ptr(UNICODE)
2051 can_raise_memoryerror = {
2052 "stroruni.concat": True,
2053 "stroruni.slice": True,
2054 "stroruni.equal": False,
2055 "stroruni.cmp": False,
2056 "stroruni.copy_string_to_raw": False,
2057 }
2058 if SoU.TO == rstr.STR:
2059 dict = {"stroruni.concat": EffectInfo.OS_STR_CONCAT,
2060 "stroruni.slice": EffectInfo.OS_STR_SLICE,
2061 "stroruni.equal": EffectInfo.OS_STR_EQUAL,
2062 "stroruni.cmp": EffectInfo.OS_STR_CMP,
2063 "stroruni.copy_string_to_raw": EffectInfo.OS_STR_COPY_TO_RAW,
2064 }
2065 CHR = lltype.Char
2066 elif SoU.TO == rstr.UNICODE:
2067 dict = {"stroruni.concat": EffectInfo.OS_UNI_CONCAT,
2068 "stroruni.slice": EffectInfo.OS_UNI_SLICE,
2069 "stroruni.equal": EffectInfo.OS_UNI_EQUAL,
2070 "stroruni.cmp": EffectInfo.OS_UNI_CMP,
2071 "stroruni.copy_string_to_raw": EffectInfo.OS_UNI_COPY_TO_RAW
2072 }
2073 CHR = lltype.UniChar
2074 elif SoU.TO == rbytearray.BYTEARRAY:
2075 raise NotSupported("bytearray operation")
2076 else:
2077 assert 0, "args[0].concretetype must be STR or UNICODE"
2078 #
2079 if oopspec_name == 'stroruni.copy_contents':
2080 if SoU.TO == rstr.STR:
2081 new_op = 'copystrcontent'
2082 elif SoU.TO == rstr.UNICODE:
2083 new_op = 'copyunicodecontent'
2084 else:
2085 assert 0
2086 return SpaceOperation(new_op, args, op.result)
2087 if oopspec_name == "stroruni.equal":
2088 for otherindex, othername, argtypes, resulttype in [
2089 (EffectInfo.OS_STREQ_SLICE_CHECKNULL,
2090 "str.eq_slice_checknull",
2091 [SoU, lltype.Signed, lltype.Signed, SoU],
2092 lltype.Signed),
2093 (EffectInfo.OS_STREQ_SLICE_NONNULL,
2094 "str.eq_slice_nonnull",
2095 [SoU, lltype.Signed, lltype.Signed, SoU],
2096 lltype.Signed),
2097 (EffectInfo.OS_STREQ_SLICE_CHAR,
2098 "str.eq_slice_char",
2099 [SoU, lltype.Signed, lltype.Signed, CHR],
2100 lltype.Signed),
2101 (EffectInfo.OS_STREQ_NONNULL,
2102 "str.eq_nonnull",
2103 [SoU, SoU],
2104 lltype.Signed),
2105 (EffectInfo.OS_STREQ_NONNULL_CHAR,
2106 "str.eq_nonnull_char",
2107 [SoU, CHR],
2108 lltype.Signed),
2109 (EffectInfo.OS_STREQ_CHECKNULL_CHAR,
2110 "str.eq_checknull_char",
2111 [SoU, CHR],
2112 lltype.Signed),
2113 (EffectInfo.OS_STREQ_LENGTHOK,
2114 "str.eq_lengthok",
2115 [SoU, SoU],
2116 lltype.Signed),
2117 ]:
2118 if args[0].concretetype.TO == rstr.UNICODE:
2119 otherindex += EffectInfo._OS_offset_uni
2120 self._register_extra_helper(otherindex, othername,
2121 argtypes, resulttype,
2122 EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
2123 #
2124 if can_raise_memoryerror[oopspec_name]:
2125 extra = EffectInfo.EF_ELIDABLE_OR_MEMORYERROR
2126 else:
2127 extra = EffectInfo.EF_ELIDABLE_CANNOT_RAISE
2128 return self._handle_oopspec_call(op, args, dict[oopspec_name], extra)
2129
2130 def _handle_str2unicode_call(self, op, oopspec_name, args):
2131 # ll_str2unicode can raise UnicodeDecodeError
2132 return self._handle_oopspec_call(op, args, EffectInfo.OS_STR2UNICODE,
2133 EffectInfo.EF_ELIDABLE_CAN_RAISE)
2134
2135 # ----------
2136 # VirtualRefs.
2137
2138 def _handle_virtual_ref_call(self, op, oopspec_name, args):
2139 return SpaceOperation(oopspec_name, list(args), op.result)
2140
2141 # -----------
2142 # rlib.libffi
2143
2144 def _handle_libffi_call(self, op, oopspec_name, args):
2145 if oopspec_name == 'libffi_call':
2146 oopspecindex = EffectInfo.OS_LIBFFI_CALL
2147 extraeffect = EffectInfo.EF_RANDOM_EFFECTS
2148 self.callcontrol.has_libffi_call = True
2149 else:
2150 assert False, 'unsupported oopspec: %s' % oopspec_name
2151 return self._handle_oopspec_call(op, args, oopspecindex, extraeffect)
2152
2153 def rewrite_op_jit_force_virtual(self, op):
2154 op0 = SpaceOperation('-live-', [], None)
2155 op1 = self._do_builtin_call(op)
2156 if isinstance(op1, list):
2157 return [op0] + op1
2158 else:
2159 return [op0, op1]
2160
2161 def rewrite_op_jit_is_virtual(self, op):
2162 raise Exception("'vref.virtual' should not be used from jit-visible code")
2163
2164 def rewrite_op_jit_force_virtualizable(self, op):
2165 # this one is for virtualizables
2166 vinfo = self.get_vinfo(op.args[0])
2167 assert vinfo is not None, (
2168 "%r is a class with _virtualizable_, but no jitdriver was found"
2169 " with a 'virtualizable' argument naming a variable of that class"
2170 % op.args[0].concretetype)
2171 self.vable_flags[op.args[0]] = op.args[2].value
2172 return []
2173
2174 def rewrite_op_jit_enter_portal_frame(self, op):
2175 return [op]
2176 def rewrite_op_jit_leave_portal_frame(self, op):
2177 return [op]
2178
2179 # ---------
2180 # ll_math.sqrt_nonneg()
2181
2182 def _handle_math_sqrt_call(self, op, oopspec_name, args):
2183 return self._handle_oopspec_call(op, args, EffectInfo.OS_MATH_SQRT,
2184 EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
2185
2186 def _handle_dict_lookup_call(self, op, oopspec_name, args):
2187 extradescr1 = self.cpu.fielddescrof(op.args[1].concretetype.TO,
2188 'entries')
2189 extradescr2 = self.cpu.arraydescrof(op.args[1].concretetype.TO.entries.TO)
2190 return self._handle_oopspec_call(op, args, EffectInfo.OS_DICT_LOOKUP,
2191 extradescr=[extradescr1, extradescr2])
2192
2193 def _handle_rgc_call(self, op, oopspec_name, args):
2194 if oopspec_name == 'rgc.ll_shrink_array':
2195 return self._handle_oopspec_call(op, args, EffectInfo.OS_SHRINK_ARRAY, EffectInfo.EF_CAN_RAISE)
2196 else:
2197 raise NotImplementedError(oopspec_name)
2198
2199 def _handle_rvmprof_call(self, op, oopspec_name, args):
2200 if oopspec_name != 'rvmprof.jitted':
2201 raise NotImplementedError(oopspec_name)
2202 c_entering = Constant(0, lltype.Signed)
2203 c_leaving = Constant(1, lltype.Signed)
2204 v_uniqueid = args[0]
2205 op1 = SpaceOperation('rvmprof_code', [c_entering, v_uniqueid], None)
2206 op2 = SpaceOperation('rvmprof_code', [c_leaving, v_uniqueid], None)
2207 #
2208 # fish fish inside the oopspec's graph for the ll_func pointer
2209 block = op.args[0].value._obj.graph.startblock
2210 while True:
2211 assert len(block.exits) == 1
2212 nextblock = block.exits[0].target
2213 if nextblock.operations == ():
2214 break
2215 block = nextblock
2216 last_op = block.operations[-1]
2217 assert last_op.opname == 'direct_call'
2218 c_ll_func = last_op.args[0]
2219 #
2220 args = [c_ll_func] + op.args[2:]
2221 ops = self.rewrite_op_direct_call(SpaceOperation('direct_call',
2222 args, op.result))
2223 return [op1] + ops + [op2]
2224
2225 def rewrite_op_ll_read_timestamp(self, op):
2226 op1 = self.prepare_builtin_call(op, "ll_read_timestamp", [])
2227 return self.handle_residual_call(op1,
2228 oopspecindex=EffectInfo.OS_MATH_READ_TIMESTAMP,
2229 extraeffect=EffectInfo.EF_CANNOT_RAISE)
2230
2231 def rewrite_op_ll_get_timestamp_unit(self, op):
2232 op1 = self.prepare_builtin_call(op, "ll_get_timestamp_unit", [])
2233 return self.handle_residual_call(op1,
2234 extraeffect=EffectInfo.EF_CANNOT_RAISE)
2235
2236 def rewrite_op_jit_force_quasi_immutable(self, op):
2237 v_inst, c_fieldname = op.args
2238 descr1 = self.cpu.fielddescrof(v_inst.concretetype.TO,
2239 c_fieldname.value)
2240 op0 = SpaceOperation('-live-', [], None)
2241 op1 = SpaceOperation('jit_force_quasi_immutable', [v_inst, descr1],
2242 None)
2243 return [op0, op1]
2244
2245 def rewrite_op_threadlocalref_get(self, op):
2246 c_offset, = op.args
2247 op1 = self.prepare_builtin_call(op, 'threadlocalref_get', [c_offset])
2248 if c_offset.value.loop_invariant:
2249 effect = EffectInfo.EF_LOOPINVARIANT
2250 else:
2251 effect = EffectInfo.EF_CANNOT_RAISE
2252 return self.handle_residual_call(op1,
2253 oopspecindex=EffectInfo.OS_THREADLOCALREF_GET,
2254 extraeffect=effect)
2255
2256 # ____________________________________________________________
2257
2258 class NotSupported(Exception):
2259 pass
2260
2261 class VirtualizableArrayField(Exception):
2262 def __str__(self):
2263 return "using virtualizable array in illegal way in %r" % (
2264 self.args[0],)
2265
2266 def is_test_calldescr(calldescr):
2267 return type(calldescr) is str or getattr(calldescr, '_for_tests_only', False)
2268
2269 def _with_prefix(prefix):
2270 result = {}
2271 for name in dir(Transformer):
2272 if name.startswith(prefix):
2273 result[name[len(prefix):]] = getattr(Transformer, name)
2274 return result
2275
2276 def keep_operation_unchanged(jtransform, op):
2277 return op
2278
2279 def _add_default_ops(rewrite_ops):
2280 # All operations present in the BlackholeInterpreter as bhimpl_xxx
2281 # but not explicitly listed in this file are supposed to be just
2282 # passed in unmodified. All other operations are forbidden.
2283 for key, value in BlackholeInterpreter.__dict__.items():
2284 if key.startswith('bhimpl_'):
2285 opname = key[len('bhimpl_'):]
2286 rewrite_ops.setdefault(opname, keep_operation_unchanged)
2287 rewrite_ops.setdefault('-live-', keep_operation_unchanged)
2288
2289 _rewrite_ops = _with_prefix('rewrite_op_')
2290 _add_default_ops(_rewrite_ops)