Debian Codegraph @

rpython/jit/codewriter/test/test_jtransform.py

raw symbols SCIP
1
2 import py
3 import random
4 from itertools import product
5
6 from rpython.flowspace.model import FunctionGraph, Block, Link, c_last_exception
7 from rpython.flowspace.model import SpaceOperation, Variable, Constant
8 from rpython.rtyper.lltypesystem import lltype, llmemory, rstr, rffi
9 from rpython.rtyper import rclass
10 from rpython.rtyper.lltypesystem.module import ll_math
11 from rpython.translator.unsimplify import varoftype
12 from rpython.jit.codewriter import heaptracker, effectinfo
13 from rpython.jit.codewriter.flatten import ListOfKind
14 from rpython.jit.codewriter.jtransform import Transformer, UnsupportedMallocFlags
15 from rpython.jit.metainterp.support import int2adr
16 from rpython.jit.metainterp.history import getkind
17
18 def const(x):
19 return Constant(x, lltype.typeOf(x))
20
21 class FakeRTyper:
22 instance_reprs = {}
23
24 class FakeCPU:
25 class tracker:
26 pass
27
28 rtyper = FakeRTyper()
29 def calldescrof(self, FUNC, ARGS, RESULT):
30 return ('calldescr', FUNC, ARGS, RESULT)
31 def fielddescrof(self, STRUCT, name):
32 return ('fielddescr', STRUCT, name)
33 def interiorfielddescrof(self, ARRAY, name):
34 return ('interiorfielddescr', ARRAY, name)
35 def arraydescrof(self, ARRAY):
36 return FakeDescr(('arraydescr', ARRAY))
37 def sizeof(self, STRUCT, vtable=None):
38 return FakeDescr(('sizedescr', STRUCT))
39
40 class FakeDescr(tuple):
41 pass
42
43 class FakeLink:
44 args = []
45 def __init__(self, exitcase):
46 self.exitcase = self.llexitcase = exitcase
47
48 class FakeResidualCallControl:
49 def guess_call_kind(self, op):
50 return 'residual'
51 def getcalldescr(self, op, oopspecindex=None, extraeffect=None,
52 extradescr=None, calling_graph=None):
53 return 'calldescr'
54 def calldescr_canraise(self, calldescr):
55 return True
56
57 class FakeRegularCallControl:
58 def guess_call_kind(self, op):
59 return 'regular'
60 def graphs_from(self, op):
61 return ['somegraph']
62 def get_jitcode(self, graph, called_from=None):
63 assert graph == 'somegraph'
64 return 'somejitcode'
65
66 class FakeResidualIndirectCallControl:
67 def guess_call_kind(self, op):
68 return 'residual'
69 def getcalldescr(self, op, **kwds):
70 return 'calldescr'
71 def calldescr_canraise(self, calldescr):
72 return True
73
74 class FakeRegularIndirectCallControl:
75 def guess_call_kind(self, op):
76 return 'regular'
77 def graphs_from(self, op):
78 return ['somegraph1', 'somegraph2']
79 def getcalldescr(self, op, **kwds):
80 return 'calldescr'
81 def get_jitcode(self, graph, called_from=None):
82 assert graph in ('somegraph1', 'somegraph2')
83 return 'somejitcode' + graph[-1]
84 def calldescr_canraise(self, calldescr):
85 return False
86
87 class FakeCallInfoCollection:
88 def __init__(self):
89 self.seen = []
90 def add(self, oopspecindex, calldescr, func):
91 self.seen.append((oopspecindex, calldescr, func))
92 def has_oopspec(self, oopspecindex):
93 for i, c, f in self.seen:
94 if i == oopspecindex:
95 return True
96 return False
97 def callinfo_for_oopspec(self, oopspecindex):
98 # assert oopspecindex == effectinfo.EffectInfo.OS_STREQ_NONNULL
99 class c:
100 class adr:
101 ptr = 1
102 return ('calldescr', c)
103
104 class FakeBuiltinCallControl:
105 def __init__(self):
106 self.callinfocollection = FakeCallInfoCollection()
107 def guess_call_kind(self, op):
108 return 'builtin'
109 def getcalldescr(self, op, oopspecindex=None, extraeffect=None,
110 extradescr=None, calling_graph=None):
111 assert oopspecindex is not None # in this test
112 EI = effectinfo.EffectInfo
113 if oopspecindex not in (EI.OS_ARRAYCOPY, EI.OS_ARRAYMOVE):
114 PSTR = lltype.Ptr(rstr.STR)
115 PUNICODE = lltype.Ptr(rstr.UNICODE)
116 INT = lltype.Signed
117 UNICHAR = lltype.UniChar
118 FLOAT = lltype.Float
119 ARRAYPTR = rffi.CArrayPtr(lltype.Char)
120 argtypes = {
121 EI.OS_MATH_SQRT: ([FLOAT], FLOAT),
122 EI.OS_STR2UNICODE:([PSTR], PUNICODE),
123 EI.OS_STR_CONCAT: ([PSTR, PSTR], PSTR),
124 EI.OS_STR_SLICE: ([PSTR, INT, INT], PSTR),
125 EI.OS_STREQ_NONNULL: ([PSTR, PSTR], INT),
126 EI.OS_UNI_CONCAT: ([PUNICODE, PUNICODE], PUNICODE),
127 EI.OS_UNI_SLICE: ([PUNICODE, INT, INT], PUNICODE),
128 EI.OS_UNI_EQUAL: ([PUNICODE, PUNICODE], lltype.Bool),
129 EI.OS_UNIEQ_SLICE_CHECKNULL:([PUNICODE, INT, INT, PUNICODE], INT),
130 EI.OS_UNIEQ_SLICE_NONNULL: ([PUNICODE, INT, INT, PUNICODE], INT),
131 EI.OS_UNIEQ_SLICE_CHAR: ([PUNICODE, INT, INT, UNICHAR], INT),
132 EI.OS_UNIEQ_NONNULL: ([PUNICODE, PUNICODE], INT),
133 EI.OS_UNIEQ_NONNULL_CHAR: ([PUNICODE, UNICHAR], INT),
134 EI.OS_UNIEQ_CHECKNULL_CHAR: ([PUNICODE, UNICHAR], INT),
135 EI.OS_UNIEQ_LENGTHOK: ([PUNICODE, PUNICODE], INT),
136 EI.OS_RAW_MALLOC_VARSIZE_CHAR: ([INT], ARRAYPTR),
137 EI.OS_RAW_FREE: ([ARRAYPTR], lltype.Void),
138 EI.OS_THREADLOCALREF_GET: ([INT], INT), # for example
139 EI.OS_INT_PY_DIV: ([INT, INT], INT),
140 EI.OS_INT_UDIV: ([INT, INT], INT),
141 EI.OS_INT_PY_MOD: ([INT, INT], INT),
142 EI.OS_INT_UMOD: ([INT, INT], INT),
143 }
144 argtypes = argtypes[oopspecindex]
145 assert argtypes[0] == [v.concretetype for v in op.args[1:]]
146 assert argtypes[1] == op.result.concretetype
147 if oopspecindex == EI.OS_STR2UNICODE:
148 assert extraeffect == EI.EF_ELIDABLE_CAN_RAISE
149 elif oopspecindex == EI.OS_RAW_MALLOC_VARSIZE_CHAR:
150 assert extraeffect == EI.EF_CAN_RAISE
151 elif oopspecindex == EI.OS_RAW_FREE:
152 assert extraeffect == EI.EF_CANNOT_RAISE
153 elif oopspecindex == EI.OS_THREADLOCALREF_GET:
154 assert extraeffect == self.expected_effect_of_threadlocalref_get
155 elif oopspecindex in (EI.OS_STR_CONCAT, EI.OS_UNI_CONCAT,
156 EI.OS_STR_SLICE, EI.OS_UNI_SLICE):
157 assert extraeffect == EI.EF_ELIDABLE_OR_MEMORYERROR
158 else:
159 assert extraeffect == EI.EF_ELIDABLE_CANNOT_RAISE
160 return 'calldescr-%d' % oopspecindex
161
162 def calldescr_canraise(self, calldescr):
163 EI = effectinfo.EffectInfo
164 if calldescr == 'calldescr-%d' % EI.OS_RAW_MALLOC_VARSIZE_CHAR:
165 return True
166 return False
167
168
169 def test_optimize_goto_if_not():
170 v1 = Variable()
171 v2 = Variable()
172 v3 = Variable(); v3.concretetype = lltype.Bool
173 sp1 = SpaceOperation('foobar', [], None)
174 sp2 = SpaceOperation('foobaz', [], None)
175 block = Block([v1, v2])
176 block.operations = [sp1, SpaceOperation('int_gt', [v1, v2], v3), sp2]
177 block.exitswitch = v3
178 block.exits = exits = [FakeLink(False), FakeLink(True)]
179 res = Transformer().optimize_goto_if_not(block)
180 assert res == True
181 assert block.operations == [sp1, sp2]
182 assert block.exitswitch == ('int_gt', v1, v2, '-live-before')
183 assert block.exits == exits
184
185 def test_optimize_goto_if_not__incoming():
186 v1 = Variable(); v1.concretetype = lltype.Bool
187 block = Block([v1])
188 block.exitswitch = v1
189 block.exits = [FakeLink(False), FakeLink(True)]
190 assert not Transformer().optimize_goto_if_not(block)
191
192 def test_optimize_goto_if_not__exit():
193 # this case occurs in practice, e.g. with RPython code like:
194 # return bool(p) and p.somefield > 0
195 v1 = Variable()
196 v2 = Variable()
197 v3 = Variable(); v3.concretetype = lltype.Bool
198 block = Block([v1, v2])
199 block.operations = [SpaceOperation('int_gt', [v1, v2], v3)]
200 block.exitswitch = v3
201 block.exits = exits = [FakeLink(False), FakeLink(True)]
202 block.exits[1].args = [v3]
203 res = Transformer().optimize_goto_if_not(block)
204 assert res == True
205 assert block.operations == []
206 assert block.exitswitch == ('int_gt', v1, v2, '-live-before')
207 assert block.exits == exits
208 assert exits[1].args == [const(True)]
209
210 def test_optimize_goto_if_not__unknownop():
211 v3 = Variable(); v3.concretetype = lltype.Bool
212 block = Block([])
213 block.operations = [SpaceOperation('foobar', [], v3)]
214 block.exitswitch = v3
215 block.exits = [FakeLink(False), FakeLink(True)]
216 assert not Transformer().optimize_goto_if_not(block)
217
218 def test_optimize_goto_if_not__ptr_eq():
219 for opname in ['ptr_eq', 'ptr_ne']:
220 v1 = Variable()
221 v2 = Variable()
222 v3 = Variable(); v3.concretetype = lltype.Bool
223 block = Block([v1, v2])
224 block.operations = [SpaceOperation(opname, [v1, v2], v3)]
225 block.exitswitch = v3
226 block.exits = exits = [FakeLink(False), FakeLink(True)]
227 res = Transformer().optimize_goto_if_not(block)
228 assert res == True
229 assert block.operations == []
230 assert block.exitswitch == (opname, v1, v2, '-live-before')
231 assert block.exits == exits
232
233 def test_optimize_goto_if_not__ptr_iszero():
234 for opname in ['ptr_iszero', 'ptr_nonzero']:
235 v1 = Variable()
236 v3 = Variable(); v3.concretetype = lltype.Bool
237 block = Block([v1])
238 block.operations = [SpaceOperation(opname, [v1], v3)]
239 block.exitswitch = v3
240 block.exits = exits = [FakeLink(False), FakeLink(True)]
241 res = Transformer().optimize_goto_if_not(block)
242 assert res == True
243 assert block.operations == []
244 assert block.exitswitch == (opname, v1, '-live-before')
245 assert block.exits == exits
246
247 def test_optimize_goto_if_not__argument_to_call():
248 for opname in ['ptr_iszero', 'ptr_nonzero']:
249 v1 = Variable()
250 v3 = Variable(); v3.concretetype = lltype.Bool
251 v4 = Variable()
252 block = Block([v1])
253 callop = SpaceOperation('residual_call_r_i',
254 ["fake", ListOfKind('int', [v3])], v4)
255 block.operations = [SpaceOperation(opname, [v1], v3), callop]
256 block.exitswitch = v3
257 block.exits = exits = [FakeLink(False), FakeLink(True)]
258 res = Transformer().optimize_goto_if_not(block)
259 assert not res
260
261 def test_symmetric():
262 ops = {'int_add': 'int_add',
263 'int_or': 'int_or',
264 'int_gt': ('int_gt', 'int_lt'),
265 'uint_eq': 'int_eq',
266 'uint_le': ('uint_le', 'uint_ge'),
267 'char_ne': 'int_ne',
268 'char_lt': ('int_lt', 'int_gt'),
269 'uint_xor': 'int_xor',
270 'float_mul': 'float_mul',
271 'float_gt': ('float_gt', 'float_lt'),
272 }
273 v3 = varoftype(lltype.Signed)
274 for v1 in [varoftype(lltype.Signed), const(42)]:
275 for v2 in [varoftype(lltype.Signed), const(43)]:
276 for name1, name2 in ops.items():
277 op = SpaceOperation(name1, [v1, v2], v3)
278 op1 = Transformer(FakeCPU()).rewrite_operation(op)
279 if isinstance(name2, str):
280 name2 = name2, name2
281 if isinstance(v1, Constant) and isinstance(v2, Variable):
282 assert op1.args == [v2, v1]
283 assert op1.result == v3
284 assert op1.opname == name2[1]
285 else:
286 assert op1.args == [v1, v2]
287 assert op1.result == v3
288 assert op1.opname == name2[0]
289
290 @py.test.mark.parametrize('opname', ['add_ovf', 'sub_ovf', 'mul_ovf'])
291 def test_int_op_ovf(opname):
292 v3 = varoftype(lltype.Signed)
293 for v1 in [varoftype(lltype.Signed), const(42)]:
294 for v2 in [varoftype(lltype.Signed), const(43)]:
295 op = SpaceOperation('int_' + opname, [v1, v2], v3)
296 oplist = Transformer(FakeCPU()).rewrite_operation(op)
297 op1, op0 = oplist
298 assert op0.opname == 'int_' + opname
299 if (isinstance(v1, Constant) and isinstance(v2, Variable)
300 and opname != 'sub_ovf'):
301 assert op0.args == [v2, v1]
302 assert op0.result == v3
303 else:
304 assert op0.args == [v1, v2]
305 assert op0.result == v3
306 assert op1.opname == '-live-'
307 assert op1.args == []
308 assert op1.result is None
309
310 def test_neg_ovf():
311 v3 = varoftype(lltype.Signed)
312 for v1 in [varoftype(lltype.Signed), const(42)]:
313 op = SpaceOperation('direct_call', [Constant('neg_ovf'), v1], v3)
314 oplist = Transformer(FakeCPU())._handle_int_special(op, 'int.neg_ovf',
315 [v1])
316 op1, op0 = oplist
317 assert op0.opname == 'int_sub_ovf'
318 assert op0.args == [Constant(0), v1]
319 assert op0.result == v3
320 assert op1.opname == '-live-'
321 assert op1.args == []
322 assert op1.result is None
323
324 @py.test.mark.parametrize('opname', ['py_div', 'udiv', 'py_mod', 'umod'])
325 def test_int_op_residual(opname):
326 v3 = varoftype(lltype.Signed)
327 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
328 for v1 in [varoftype(lltype.Signed), const(42)]:
329 for v2 in [varoftype(lltype.Signed), const(43)]:
330 op = SpaceOperation('direct_call', [Constant(opname), v1, v2], v3)
331 op0 = tr._handle_int_special(op, 'int.'+opname, [v1, v2])
332 assert op0.opname == 'residual_call_ir_i'
333 assert op0.args[0].value == opname # pseudo-function as str
334 expected = ('int_' + opname).upper()
335 assert (op0.args[-1] == 'calldescr-%d' %
336 getattr(effectinfo.EffectInfo, 'OS_' + expected))
337
338 def test_calls():
339 for RESTYPE, with_void, with_i, with_r, with_f in product(
340 [lltype.Signed, rclass.OBJECTPTR, lltype.Float, lltype.Void],
341 [False, True],
342 [False, True],
343 [False, True],
344 [False, True],
345 ):
346 ARGS = []
347 if with_void:
348 ARGS += [lltype.Void, lltype.Void]
349 if with_i:
350 ARGS += [lltype.Signed, lltype.Char]
351 if with_r:
352 ARGS += [rclass.OBJECTPTR, lltype.Ptr(rstr.STR)]
353 if with_f:
354 ARGS += [lltype.Float, lltype.Float]
355 random.shuffle(ARGS)
356 if RESTYPE == lltype.Float:
357 with_f = True
358 if with_f:
359 expectedkind = 'irf' # all kinds
360 elif with_i:
361 expectedkind = 'ir' # integers and references
362 else:
363 expectedkind = 'r' # only references
364 yield residual_call_test, ARGS, RESTYPE, expectedkind
365 yield direct_call_test, ARGS, RESTYPE, expectedkind
366 yield indirect_residual_call_test, ARGS, RESTYPE, expectedkind
367 yield indirect_regular_call_test, ARGS, RESTYPE, expectedkind
368
369 def get_direct_call_op(argtypes, restype):
370 FUNC = lltype.FuncType(argtypes, restype)
371 fnptr = lltype.functionptr(FUNC, "g") # no graph
372 c_fnptr = const(fnptr)
373 vars = [varoftype(TYPE) for TYPE in argtypes]
374 v_result = varoftype(restype)
375 op = SpaceOperation('direct_call', [c_fnptr] + vars, v_result)
376 return op
377
378 def residual_call_test(argtypes, restype, expectedkind):
379 op = get_direct_call_op(argtypes, restype)
380 tr = Transformer(FakeCPU(), FakeResidualCallControl())
381 oplist = tr.rewrite_operation(op)
382 op0, op1 = oplist
383 reskind = getkind(restype)[0]
384 assert op0.opname == 'residual_call_%s_%s' % (expectedkind, reskind)
385 assert op0.result == op.result
386 assert op0.args[0] == op.args[0]
387 assert op0.args[-1] == 'calldescr'
388 assert len(op0.args) == 1 + len(expectedkind) + 1
389 for sublist, kind1 in zip(op0.args[1:-1], expectedkind):
390 assert sublist.kind.startswith(kind1)
391 assert list(sublist) == [v for v in op.args[1:]
392 if getkind(v.concretetype) == sublist.kind]
393 for v in op.args[1:]:
394 kind = getkind(v.concretetype)
395 assert kind == 'void' or kind[0] in expectedkind
396 assert op1.opname == '-live-'
397 assert op1.args == []
398
399 def direct_call_test(argtypes, restype, expectedkind):
400 op = get_direct_call_op(argtypes, restype)
401 tr = Transformer(FakeCPU(), FakeRegularCallControl())
402 tr.graph = 'someinitialgraph'
403 oplist = tr.rewrite_operation(op)
404 op0, op1 = oplist
405 reskind = getkind(restype)[0]
406 assert op0.opname == 'inline_call_%s_%s' % (expectedkind, reskind)
407 assert op0.result == op.result
408 assert op0.args[0] == 'somejitcode'
409 assert len(op0.args) == 1 + len(expectedkind)
410 for sublist, kind1 in zip(op0.args[1:], expectedkind):
411 assert sublist.kind.startswith(kind1)
412 assert list(sublist) == [v for v in op.args[1:]
413 if getkind(v.concretetype) == sublist.kind]
414 for v in op.args[1:]:
415 kind = getkind(v.concretetype)
416 assert kind == 'void' or kind[0] in expectedkind
417 assert op1.opname == '-live-'
418 assert op1.args == []
419
420 def indirect_residual_call_test(argtypes, restype, expectedkind):
421 # an indirect call that is residual in all cases is very similar to
422 # a residual direct call
423 op = get_direct_call_op(argtypes, restype)
424 op.opname = 'indirect_call'
425 op.args[0] = varoftype(op.args[0].concretetype)
426 op.args.append(Constant(['somegraph1', 'somegraph2'], lltype.Void))
427 tr = Transformer(FakeCPU(), FakeResidualIndirectCallControl())
428 tr.graph = 'someinitialgraph'
429 oplist = tr.rewrite_operation(op)
430 op0, op1 = oplist
431 reskind = getkind(restype)[0]
432 assert op0.opname == 'residual_call_%s_%s' % (expectedkind, reskind)
433 assert op0.result == op.result
434 assert op0.args[0] == op.args[0]
435 assert op0.args[-1] == 'calldescr'
436 assert len(op0.args) == 1 + len(expectedkind) + 1
437 for sublist, kind1 in zip(op0.args[1:-1], expectedkind):
438 assert sublist.kind.startswith(kind1)
439 assert list(sublist) == [v for v in op.args[1:]
440 if getkind(v.concretetype)==sublist.kind]
441 for v in op.args[1:]:
442 kind = getkind(v.concretetype)
443 assert kind == 'void' or kind[0] in expectedkind
444 assert op1.opname == '-live-'
445 assert op1.args == []
446
447 def indirect_regular_call_test(argtypes, restype, expectedkind):
448 # a regular indirect call is preceded by a guard_value on the
449 # function address, so that pyjitpl can know which jitcode to follow
450 from rpython.jit.codewriter.flatten import IndirectCallTargets
451 op = get_direct_call_op(argtypes, restype)
452 op.opname = 'indirect_call'
453 op.args[0] = varoftype(op.args[0].concretetype)
454 op.args.append(Constant(['somegraph1', 'somegraph2'], lltype.Void))
455 tr = Transformer(FakeCPU(), FakeRegularIndirectCallControl())
456 tr.graph = 'someinitialgraph'
457 oplist = tr.rewrite_operation(op)
458 op0gv, op1gv, op0, op1 = oplist
459 assert op0gv.opname == '-live-'
460 assert op0gv.args == []
461 assert op1gv.opname == 'int_guard_value'
462 assert op1gv.args == [op.args[0]]
463 assert op1gv.result is None
464 #
465 reskind = getkind(restype)[0]
466 assert op0.opname == 'residual_call_%s_%s' % (expectedkind, reskind)
467 assert op0.result == op.result
468 assert op0.args[0] == op.args[0]
469 assert isinstance(op0.args[1], IndirectCallTargets)
470 assert op0.args[1].lst == ['somejitcode1', 'somejitcode2']
471 assert op0.args[-1] == 'calldescr'
472 assert len(op0.args) == 2 + len(expectedkind) + 1
473 for sublist, kind1 in zip(op0.args[2:-1], expectedkind):
474 assert sublist.kind.startswith(kind1)
475 assert list(sublist) == [v for v in op.args[1:]
476 if getkind(v.concretetype)==sublist.kind]
477 for v in op.args[1:]:
478 kind = getkind(v.concretetype)
479 assert kind == 'void' or kind[0] in expectedkind
480 # Note: we still expect a -live- here, even though canraise() returns
481 # False, because this 'residual_call' will likely call further jitcodes
482 # which can do e.g. guard_class or other stuff requiring anyway a -live-.
483 assert op1.opname == '-live-'
484 assert op1.args == []
485
486 def test_getfield():
487 # XXX a more compact encoding would be possible, something along
488 # the lines of getfield_gc_r %r0, $offset, %r1
489 # which would not need a Descr at all.
490 S1 = lltype.Struct('S1')
491 S2 = lltype.GcStruct('S2')
492 S = lltype.GcStruct('S', ('int', lltype.Signed),
493 ('ps1', lltype.Ptr(S1)),
494 ('ps2', lltype.Ptr(S2)),
495 ('flt', lltype.Float),
496 ('boo', lltype.Bool),
497 ('chr', lltype.Char),
498 ('unc', lltype.UniChar))
499 for name, suffix in [('int', 'i'),
500 ('ps1', 'i'),
501 ('ps2', 'r'),
502 ('flt', 'f'),
503 ('boo', 'i'),
504 ('chr', 'i'),
505 ('unc', 'i')]:
506 v_parent = varoftype(lltype.Ptr(S))
507 c_name = Constant(name, lltype.Void)
508 v_result = varoftype(getattr(S, name))
509 op = SpaceOperation('getfield', [v_parent, c_name], v_result)
510 op1 = Transformer(FakeCPU()).rewrite_operation(op)
511 assert op1.opname == 'getfield_gc_' + suffix
512 fielddescr = ('fielddescr', S, name)
513 assert op1.args == [v_parent, fielddescr]
514 assert op1.result == v_result
515
516 def test_getfield_typeptr():
517 v_parent = varoftype(rclass.OBJECTPTR)
518 c_name = Constant('typeptr', lltype.Void)
519 v_result = varoftype(rclass.OBJECT.typeptr)
520 op = SpaceOperation('getfield', [v_parent, c_name], v_result)
521 oplist = Transformer(FakeCPU()).rewrite_operation(op)
522 op0, op1 = oplist
523 assert op0.opname == '-live-'
524 assert op0.args == []
525 assert op1.opname == 'guard_class'
526 assert op1.args == [v_parent]
527 assert op1.result == v_result
528
529 def test_setfield():
530 # XXX a more compact encoding would be possible; see test_getfield()
531 S1 = lltype.Struct('S1')
532 S2 = lltype.GcStruct('S2')
533 S = lltype.GcStruct('S', ('int', lltype.Signed),
534 ('ps1', lltype.Ptr(S1)),
535 ('ps2', lltype.Ptr(S2)),
536 ('flt', lltype.Float),
537 ('boo', lltype.Bool),
538 ('chr', lltype.Char),
539 ('unc', lltype.UniChar))
540 for name, suffix in [('int', 'i'),
541 ('ps1', 'i'),
542 ('ps2', 'r'),
543 ('flt', 'f'),
544 ('boo', 'i'),
545 ('chr', 'i'),
546 ('unc', 'i')]:
547 v_parent = varoftype(lltype.Ptr(S))
548 c_name = Constant(name, lltype.Void)
549 v_newvalue = varoftype(getattr(S, name))
550 op = SpaceOperation('setfield', [v_parent, c_name, v_newvalue],
551 varoftype(lltype.Void))
552 op1 = Transformer(FakeCPU()).rewrite_operation(op)
553 assert op1.opname == 'setfield_gc_' + suffix
554 fielddescr = ('fielddescr', S, name)
555 assert op1.args == [v_parent, v_newvalue, fielddescr]
556 assert op1.result is None
557
558 def test_malloc_new():
559 S = lltype.GcStruct('S')
560 v = varoftype(lltype.Ptr(S))
561 op = SpaceOperation('malloc', [Constant(S, lltype.Void),
562 Constant({'flavor': 'gc'}, lltype.Void)], v)
563 op1 = Transformer(FakeCPU()).rewrite_operation(op)
564 assert op1.opname == 'new'
565 assert op1.args == [('sizedescr', S)]
566
567 def test_malloc_new_zero_2():
568 S = lltype.GcStruct('S', ('x', lltype.Signed))
569 v = varoftype(lltype.Ptr(S))
570 op = SpaceOperation('malloc', [Constant(S, lltype.Void),
571 Constant({'flavor': 'gc',
572 'zero': True}, lltype.Void)], v)
573 op1, op2 = Transformer(FakeCPU()).rewrite_operation(op)
574 assert op1.opname == 'new'
575 assert op1.args == [('sizedescr', S)]
576 assert op2.opname == 'setfield_gc_i'
577 assert op2.args[0] == v
578
579 def test_malloc_new_zero_nested():
580 S0 = lltype.GcStruct('S0')
581 S = lltype.Struct('S', ('x', lltype.Ptr(S0)))
582 S2 = lltype.GcStruct('S2', ('parent', S),
583 ('xx', lltype.Ptr(S0)))
584 v = varoftype(lltype.Ptr(S2))
585 op = SpaceOperation('malloc', [Constant(S2, lltype.Void),
586 Constant({'flavor': 'gc',
587 'zero': True}, lltype.Void)], v)
588 op1, op2, op3 = Transformer(FakeCPU()).rewrite_operation(op)
589 assert op1.opname == 'new'
590 assert op1.args == [('sizedescr', S2)]
591 assert op2.opname == 'setfield_gc_r'
592 assert op2.args[0] == v
593 assert op3.opname == 'setfield_gc_r'
594 assert op3.args[0] == v
595
596 def test_malloc_new_with_vtable():
597 vtable = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
598 S = lltype.GcStruct('S', ('parent', rclass.OBJECT))
599 heaptracker.set_testing_vtable_for_gcstruct(S, vtable, 'S')
600 v = varoftype(lltype.Ptr(S))
601 op = SpaceOperation('malloc', [Constant(S, lltype.Void),
602 Constant({'flavor': 'gc'}, lltype.Void)], v)
603 cpu = FakeCPU()
604 op1 = Transformer(cpu).rewrite_operation(op)
605 assert op1.opname == 'new_with_vtable'
606 assert op1.args == [('sizedescr', S)]
607
608 def test_malloc_new_with_destructor():
609 vtable = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
610 S = lltype.GcStruct('S', ('parent', rclass.OBJECT), rtti=True)
611 DESTRUCTOR = lltype.FuncType([lltype.Ptr(S)], lltype.Void)
612 destructor = lltype.functionptr(DESTRUCTOR, 'destructor')
613 lltype.attachRuntimeTypeInfo(S, destrptr=destructor)
614 heaptracker.set_testing_vtable_for_gcstruct(S, vtable, 'S')
615 v = varoftype(lltype.Ptr(S))
616 op = SpaceOperation('malloc', [Constant(S, lltype.Void),
617 Constant({'flavor': 'gc'}, lltype.Void)], v)
618 tr = Transformer(FakeCPU(), FakeResidualCallControl())
619 oplist = tr.rewrite_operation(op)
620 op0, op1 = oplist
621 assert op0.opname == 'residual_call_r_r'
622 assert op0.args[0].value == 'alloc_with_del' # pseudo-function as a str
623 assert list(op0.args[1]) == []
624 assert op1.opname == '-live-'
625 assert op1.args == []
626
627 def test_raw_malloc():
628 S = rffi.CArray(lltype.Char)
629 v1 = varoftype(lltype.Signed)
630 v = varoftype(lltype.Ptr(S))
631 flags = Constant({'flavor': 'raw'}, lltype.Void)
632 op = SpaceOperation('malloc_varsize', [Constant(S, lltype.Void), flags,
633 v1], v)
634 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
635 op0, op1 = tr.rewrite_operation(op)
636 assert op0.opname == 'residual_call_ir_i'
637 assert op0.args[0].value == 'raw_malloc_varsize' # pseudo-function as a str
638 assert (op0.args[-1] == 'calldescr-%d' %
639 effectinfo.EffectInfo.OS_RAW_MALLOC_VARSIZE_CHAR)
640
641 assert op1.opname == '-live-'
642 assert op1.args == []
643
644 def test_raw_malloc_zero():
645 S = rffi.CArray(lltype.Signed)
646 v1 = varoftype(lltype.Signed)
647 v = varoftype(lltype.Ptr(S))
648 flags = Constant({'flavor': 'raw', 'zero': True}, lltype.Void)
649 op = SpaceOperation('malloc_varsize', [Constant(S, lltype.Void), flags,
650 v1], v)
651 tr = Transformer(FakeCPU(), FakeResidualCallControl())
652 op0, op1 = tr.rewrite_operation(op)
653 assert op0.opname == 'residual_call_ir_i'
654 assert op0.args[0].value == 'raw_malloc_varsize_zero' # pseudo-fn as a str
655 assert op1.opname == '-live-'
656 assert op1.args == []
657
658 def test_raw_malloc_unsupported_flag():
659 S = rffi.CArray(lltype.Signed)
660 v1 = varoftype(lltype.Signed)
661 v = varoftype(lltype.Ptr(S))
662 flags = Constant({'flavor': 'raw', 'unsupported_flag': True}, lltype.Void)
663 op = SpaceOperation('malloc_varsize', [Constant(S, lltype.Void), flags,
664 v1], v)
665 tr = Transformer(FakeCPU(), FakeResidualCallControl())
666 py.test.raises(UnsupportedMallocFlags, tr.rewrite_operation, op)
667
668 def test_raw_malloc_fixedsize():
669 S = lltype.Struct('dummy', ('x', lltype.Signed))
670 v = varoftype(lltype.Ptr(S))
671 flags = Constant({'flavor': 'raw', 'zero': True}, lltype.Void)
672 op = SpaceOperation('malloc', [Constant(S, lltype.Void), flags], v)
673 tr = Transformer(FakeCPU(), FakeResidualCallControl())
674 op0, op1 = tr.rewrite_operation(op)
675 assert op0.opname == 'residual_call_r_i'
676 assert op0.args[0].value == 'raw_malloc_fixedsize_zero' #pseudo-fn as a str
677 assert op1.opname == '-live-'
678 assert op1.args == []
679
680 def test_raw_free():
681 S = rffi.CArray(lltype.Char)
682 flags = Constant({'flavor': 'raw', 'track_allocation': True},
683 lltype.Void)
684 op = SpaceOperation('free', [varoftype(lltype.Ptr(S)), flags],
685 varoftype(lltype.Void))
686 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
687 op0 = tr.rewrite_operation(op)
688 assert op0.opname == 'residual_call_ir_v'
689 assert op0.args[0].value == 'raw_free'
690 assert op0.args[-1] == 'calldescr-%d' % effectinfo.EffectInfo.OS_RAW_FREE
691
692 def test_raw_free_no_track_allocation():
693 S = rffi.CArray(lltype.Signed)
694 flags = Constant({'flavor': 'raw', 'track_allocation': False},
695 lltype.Void)
696 op = SpaceOperation('free', [varoftype(lltype.Ptr(S)), flags],
697 varoftype(lltype.Void))
698 tr = Transformer(FakeCPU(), FakeResidualCallControl())
699 op0, op1 = tr.rewrite_operation(op)
700 assert op0.opname == 'residual_call_ir_v'
701 assert op0.args[0].value == 'raw_free_no_track_allocation'
702 assert op1.opname == '-live-'
703
704 def test_rename_on_links():
705 v1 = Variable()
706 v2 = Variable(); v2.concretetype = llmemory.Address
707 v3 = Variable()
708 block = Block([v1])
709 block.operations = [SpaceOperation('cast_pointer', [v1], v2)]
710 block2 = Block([v3])
711 block.closeblock(Link([v2], block2))
712 Transformer().optimize_block(block)
713 assert block.inputargs == [v1]
714 assert block.operations == []
715 assert block.exits[0].target is block2
716 assert block.exits[0].args == [v1]
717
718 def test_cast_pointer_trash():
719 from rpython.rtyper.lltypesystem import lltype
720 S2 = lltype.GcStruct("s2", ('a', lltype.Signed))
721 S1 = lltype.GcStruct("s1", ('sub1', S2))
722 p2 = lltype.malloc(S2)
723 p2.a = 12
724 def f():
725 return lltype.cast_pointer(lltype.Ptr(S1), p2)
726 block = Block([])
727 const_p2 = const(p2)
728 v2 = Variable()
729 v3 = Variable()
730 v2.concretetype = lltype.Ptr(S1)
731 block.operations = [SpaceOperation('cast_pointer', [const_p2], v2)]
732 block2 = Block([v3])
733 block.closeblock(Link([v2], block2))
734 Transformer().optimize_block(block)
735
736 def test_cast_ptr_to_adr():
737 t = Transformer(FakeCPU(), None)
738 v = varoftype(lltype.Ptr(lltype.Array()))
739 v2 = varoftype(llmemory.Address)
740 op1 = t.rewrite_operation(SpaceOperation('cast_ptr_to_adr', [v], v2))
741 assert op1 is None
742
743 def test_int_eq():
744 v1 = varoftype(lltype.Signed)
745 v2 = varoftype(lltype.Signed)
746 v3 = varoftype(lltype.Bool)
747 c0 = const(0)
748 #
749 for opname, reducedname in [('int_eq', 'int_is_zero'),
750 ('int_ne', 'int_is_true')]:
751 op = SpaceOperation(opname, [v1, v2], v3)
752 op1 = Transformer().rewrite_operation(op)
753 assert op1.opname == opname
754 assert op1.args == [v1, v2]
755 #
756 op = SpaceOperation(opname, [v1, c0], v3)
757 op1 = Transformer().rewrite_operation(op)
758 assert op1.opname == reducedname
759 assert op1.args == [v1]
760 #
761 op = SpaceOperation(opname, [c0, v2], v3)
762 op1 = Transformer().rewrite_operation(op)
763 assert op1.opname == reducedname
764 assert op1.args == [v2]
765
766 def test_ptr_eq():
767 v1 = varoftype(lltype.Ptr(rstr.STR))
768 v2 = varoftype(lltype.Ptr(rstr.STR))
769 v3 = varoftype(lltype.Bool)
770 c0 = const(lltype.nullptr(rstr.STR))
771 #
772 for opname, reducedname in [('ptr_eq', 'ptr_iszero'),
773 ('ptr_ne', 'ptr_nonzero')]:
774 op = SpaceOperation(opname, [v1, v2], v3)
775 op1 = Transformer().rewrite_operation(op)
776 assert op1.opname == opname
777 assert op1.args == [v1, v2]
778 #
779 op = SpaceOperation(opname, [v1, c0], v3)
780 op1 = Transformer().rewrite_operation(op)
781 assert op1.opname == reducedname
782 assert op1.args == [v1]
783 #
784 op = SpaceOperation(opname, [c0, v2], v3)
785 op1 = Transformer().rewrite_operation(op)
786 assert op1.opname == reducedname
787 assert op1.args == [v2]
788
789 def test_instance_ptr_eq():
790 v1 = varoftype(rclass.OBJECTPTR)
791 v2 = varoftype(rclass.OBJECTPTR)
792 v3 = varoftype(lltype.Bool)
793 c0 = const(lltype.nullptr(rclass.OBJECT))
794
795 for opname, newopname, reducedname in [
796 ('ptr_eq', 'instance_ptr_eq', 'ptr_iszero'),
797 ('ptr_ne', 'instance_ptr_ne', 'ptr_nonzero')
798 ]:
799 op = SpaceOperation(opname, [v1, v2], v3)
800 op1 = Transformer().rewrite_operation(op)
801 assert op1.opname == newopname
802 assert op1.args == [v1, v2]
803
804 op = SpaceOperation(opname, [v1, c0], v3)
805 op1 = Transformer().rewrite_operation(op)
806 assert op1.opname == reducedname
807 assert op1.args == [v1]
808
809 op = SpaceOperation(opname, [c0, v1], v3)
810 op1 = Transformer().rewrite_operation(op)
811 assert op1.opname == reducedname
812 assert op1.args == [v1]
813
814 def test_nongc_ptr_eq():
815 v1 = varoftype(rclass.NONGCOBJECTPTR)
816 v2 = varoftype(rclass.NONGCOBJECTPTR)
817 v3 = varoftype(lltype.Bool)
818 c0 = const(lltype.nullptr(rclass.NONGCOBJECT))
819 #
820 for opname, reducedname in [('ptr_eq', 'int_is_zero'),
821 ('ptr_ne', 'int_is_true')]:
822 op = SpaceOperation(opname, [v1, v2], v3)
823 op1 = Transformer().rewrite_operation(op)
824 assert op1.opname == opname.replace('ptr_', 'int_')
825 assert op1.args == [v1, v2]
826 #
827 op = SpaceOperation(opname, [v1, c0], v3)
828 op1 = Transformer().rewrite_operation(op)
829 assert op1.opname == reducedname
830 assert op1.args == [v1]
831 #
832 op = SpaceOperation(opname, [c0, v2], v3)
833 op1 = Transformer().rewrite_operation(op)
834 assert op1.opname == reducedname
835 assert op1.args == [v2]
836 #
837 op = SpaceOperation('ptr_iszero', [v1], v3)
838 op1 = Transformer().rewrite_operation(op)
839 assert op1.opname == 'int_is_zero'
840 assert op1.args == [v1]
841 #
842 op = SpaceOperation('ptr_nonzero', [v1], v3)
843 op1 = Transformer().rewrite_operation(op)
844 assert op1.opname == 'int_is_true'
845 assert op1.args == [v1]
846
847 def test_str_getinteriorarraysize():
848 v = varoftype(lltype.Ptr(rstr.STR))
849 v_result = varoftype(lltype.Signed)
850 op = SpaceOperation('getinteriorarraysize',
851 [v, Constant('chars', lltype.Void)],
852 v_result)
853 op1 = Transformer().rewrite_operation(op)
854 assert op1.opname == 'strlen'
855 assert op1.args == [v]
856 assert op1.result == v_result
857
858 def test_unicode_getinteriorarraysize():
859 v = varoftype(lltype.Ptr(rstr.UNICODE))
860 v_result = varoftype(lltype.Signed)
861 op = SpaceOperation('getinteriorarraysize',
862 [v, Constant('chars', lltype.Void)],
863 v_result)
864 op1 = Transformer().rewrite_operation(op)
865 assert op1.opname == 'unicodelen'
866 assert op1.args == [v]
867 assert op1.result == v_result
868
869 def test_str_getinteriorfield():
870 v = varoftype(lltype.Ptr(rstr.STR))
871 v_index = varoftype(lltype.Signed)
872 v_result = varoftype(lltype.Char)
873 op = SpaceOperation('getinteriorfield',
874 [v, Constant('chars', lltype.Void), v_index],
875 v_result)
876 op1 = Transformer().rewrite_operation(op)
877 assert op1.opname == 'strgetitem'
878 assert op1.args == [v, v_index]
879 assert op1.result == v_result
880
881 def test_unicode_getinteriorfield():
882 v = varoftype(lltype.Ptr(rstr.UNICODE))
883 v_index = varoftype(lltype.Signed)
884 v_result = varoftype(lltype.UniChar)
885 op = SpaceOperation('getinteriorfield',
886 [v, Constant('chars', lltype.Void), v_index],
887 v_result)
888 op1 = Transformer().rewrite_operation(op)
889 assert op1.opname == 'unicodegetitem'
890 assert op1.args == [v, v_index]
891 assert op1.result == v_result
892
893 def test_dict_getinteriorfield():
894 DICT = lltype.GcArray(lltype.Struct('ENTRY', ('v', lltype.Signed),
895 ('k', lltype.Signed)))
896 v = varoftype(lltype.Ptr(DICT))
897 i = varoftype(lltype.Signed)
898 v_result = varoftype(lltype.Signed)
899 op = SpaceOperation('getinteriorfield', [v, i, Constant('v', lltype.Void)],
900 v_result)
901 op1 = Transformer(FakeCPU()).rewrite_operation(op)
902 assert op1.opname == 'getinteriorfield_gc_i'
903 assert op1.args == [v, i, ('interiorfielddescr', DICT, 'v')]
904 op = SpaceOperation('getinteriorfield', [v, i, Constant('v', lltype.Void)],
905 Constant(None, lltype.Void))
906 op1 = Transformer(FakeCPU()).rewrite_operation(op)
907 assert op1 is None
908
909 def test_str_setinteriorfield():
910 v = varoftype(lltype.Ptr(rstr.STR))
911 v_index = varoftype(lltype.Signed)
912 v_newchr = varoftype(lltype.Char)
913 v_void = varoftype(lltype.Void)
914 op = SpaceOperation('setinteriorfield',
915 [v, Constant('chars', lltype.Void), v_index, v_newchr],
916 v_void)
917 op1 = Transformer().rewrite_operation(op)
918 assert op1.opname == 'strsetitem'
919 assert op1.args == [v, v_index, v_newchr]
920 assert op1.result == v_void
921
922 def test_unicode_setinteriorfield():
923 v = varoftype(lltype.Ptr(rstr.UNICODE))
924 v_index = varoftype(lltype.Signed)
925 v_newchr = varoftype(lltype.UniChar)
926 v_void = varoftype(lltype.Void)
927 op = SpaceOperation('setinteriorfield',
928 [v, Constant('chars', lltype.Void), v_index, v_newchr],
929 v_void)
930 op1 = Transformer().rewrite_operation(op)
931 assert op1.opname == 'unicodesetitem'
932 assert op1.args == [v, v_index, v_newchr]
933 assert op1.result == v_void
934
935 def test_dict_setinteriorfield():
936 DICT = lltype.GcArray(lltype.Struct('ENTRY', ('v', lltype.Signed),
937 ('k', lltype.Signed)))
938 v = varoftype(lltype.Ptr(DICT))
939 i = varoftype(lltype.Signed)
940 v_void = varoftype(lltype.Void)
941 op = SpaceOperation('setinteriorfield', [v, i, Constant('v', lltype.Void),
942 i],
943 v_void)
944 op1 = Transformer(FakeCPU()).rewrite_operation(op)
945 assert op1.opname == 'setinteriorfield_gc_i'
946 assert op1.args == [v, i, i, ('interiorfielddescr', DICT, 'v')]
947 op = SpaceOperation('setinteriorfield', [v, i, Constant('v', lltype.Void),
948 v_void], v_void)
949 op1 = Transformer(FakeCPU()).rewrite_operation(op)
950 assert not op1
951
952 def test_raw_store():
953 v_storage = varoftype(llmemory.Address)
954 v_index = varoftype(lltype.Signed)
955 v_item = varoftype(lltype.Signed) # for example
956 op = SpaceOperation('raw_store', [v_storage, v_index, v_item], None)
957 op1 = Transformer(FakeCPU()).rewrite_operation(op)
958 assert op1.opname == 'raw_store_i'
959 assert op1.args[0] == v_storage
960 assert op1.args[1] == v_index
961 assert op1.args[2] == v_item
962 assert op1.args[3] == ('arraydescr', rffi.CArray(lltype.Signed))
963
964 def test_raw_load():
965 v_storage = varoftype(llmemory.Address)
966 v_index = varoftype(lltype.Signed)
967 v_res = varoftype(lltype.Signed) # for example
968 op = SpaceOperation('raw_load', [v_storage, v_index], v_res)
969 op1 = Transformer(FakeCPU()).rewrite_operation(op)
970 assert op1.opname == 'raw_load_i'
971 assert op1.args[0] == v_storage
972 assert op1.args[1] == v_index
973 assert op1.args[2] == ('arraydescr', rffi.CArray(lltype.Signed))
974 assert op1.result == v_res
975
976 def test_promote_1():
977 v1 = varoftype(lltype.Signed)
978 v2 = varoftype(lltype.Signed)
979 op = SpaceOperation('hint',
980 [v1, Constant({'promote': True}, lltype.Void)],
981 v2)
982 oplist = Transformer().rewrite_operation(op)
983 op0, op1, op2 = oplist
984 assert op0.opname == '-live-'
985 assert op0.args == []
986 assert op1.opname == 'int_guard_value'
987 assert op1.args == [v1]
988 assert op1.result is None
989 assert op2 is None
990
991 def test_promote_2():
992 v1 = varoftype(lltype.Signed)
993 v2 = varoftype(lltype.Signed)
994 op = SpaceOperation('hint',
995 [v1, Constant({'promote': True}, lltype.Void)],
996 v2)
997 returnblock = Block([varoftype(lltype.Signed)])
998 returnblock.operations = ()
999 block = Block([v1])
1000 block.operations = [op]
1001 block.closeblock(Link([v2], returnblock))
1002 Transformer().optimize_block(block)
1003 assert len(block.operations) == 2
1004 assert block.operations[0].opname == '-live-'
1005 assert block.operations[0].args == []
1006 assert block.operations[1].opname == 'int_guard_value'
1007 assert block.operations[1].args == [v1]
1008 assert block.operations[1].result is None
1009 assert block.exits[0].args == [v1]
1010
1011 def test_jit_merge_point_1():
1012 class FakeJitDriverSD:
1013 index = 42
1014 class jitdriver:
1015 active = True
1016 greens = ['green1', 'green2', 'voidgreen3']
1017 reds = ['red1', 'red2', 'voidred3']
1018 numreds = 3
1019 jd = FakeJitDriverSD()
1020 v1 = varoftype(lltype.Signed)
1021 v2 = varoftype(lltype.Signed)
1022 vvoid1 = varoftype(lltype.Void)
1023 v3 = varoftype(lltype.Signed)
1024 v4 = varoftype(lltype.Signed)
1025 vvoid2 = varoftype(lltype.Void)
1026 v5 = varoftype(lltype.Void)
1027 op = SpaceOperation('jit_marker',
1028 [Constant('jit_merge_point', lltype.Void),
1029 Constant(jd.jitdriver, lltype.Void),
1030 v1, v2, vvoid1, v3, v4, vvoid2], v5)
1031 tr = Transformer()
1032 tr.portal_jd = jd
1033 oplist = tr.rewrite_operation(op)
1034 assert len(oplist) == 7
1035 assert oplist[0].opname == '-live-'
1036 assert oplist[1].opname == 'int_guard_value'
1037 assert oplist[1].args == [v1]
1038 assert oplist[2].opname == '-live-'
1039 assert oplist[3].opname == 'int_guard_value'
1040 assert oplist[3].args == [v2]
1041 assert oplist[4].opname == '-live-'
1042 assert oplist[5].opname == 'jit_merge_point'
1043 assert oplist[5].args[0].value == 42
1044 assert list(oplist[5].args[1]) == [v1, v2]
1045 assert list(oplist[5].args[4]) == [v3, v4]
1046 assert oplist[6].opname == '-live-'
1047
1048 def test_getfield_gc():
1049 S = lltype.GcStruct('S', ('x', lltype.Char))
1050 v1 = varoftype(lltype.Ptr(S))
1051 v2 = varoftype(lltype.Char)
1052 op = SpaceOperation('getfield', [v1, Constant('x', lltype.Void)], v2)
1053 op1 = Transformer(FakeCPU()).rewrite_operation(op)
1054 assert op1.opname == 'getfield_gc_i'
1055 assert op1.args == [v1, ('fielddescr', S, 'x')]
1056 assert op1.result == v2
1057
1058 def test_getfield_gc_pure():
1059 S = lltype.GcStruct('S', ('x', lltype.Char),
1060 hints={'immutable': True})
1061 v1 = varoftype(lltype.Ptr(S))
1062 v2 = varoftype(lltype.Char)
1063 op = SpaceOperation('getfield', [v1, Constant('x', lltype.Void)], v2)
1064 op1 = Transformer(FakeCPU()).rewrite_operation(op)
1065 assert op1.opname == 'getfield_gc_i_pure'
1066 assert op1.args == [v1, ('fielddescr', S, 'x')]
1067 assert op1.result == v2
1068
1069 def test_getfield_gc_greenfield():
1070 class FakeCC:
1071 def get_vinfo(self, v):
1072 return None
1073 def could_be_green_field(self, S1, name1):
1074 assert S1 == S
1075 assert name1 == 'x'
1076 return True
1077 S = lltype.GcStruct('S', ('x', lltype.Char),
1078 hints={'immutable': True})
1079 v1 = varoftype(lltype.Ptr(S))
1080 v2 = varoftype(lltype.Char)
1081 op = SpaceOperation('getfield', [v1, Constant('x', lltype.Void)], v2)
1082 op0, op1 = Transformer(FakeCPU(), FakeCC()).rewrite_operation(op)
1083 assert op0.opname == '-live-'
1084 assert op1.opname == 'getfield_gc_i_greenfield'
1085 assert op1.args == [v1, ('fielddescr', S, 'x')]
1086 assert op1.result == v2
1087
1088 def test_int_abs():
1089 v1 = varoftype(lltype.Signed)
1090 v2 = varoftype(lltype.Signed)
1091 op = SpaceOperation('int_abs', [v1], v2)
1092 tr = Transformer(FakeCPU(), FakeRegularCallControl())
1093 tr.graph = "somemaingraph"
1094 oplist = tr.rewrite_operation(op)
1095 assert oplist[0].opname == 'inline_call_ir_i'
1096 assert oplist[0].args[0] == 'somejitcode'
1097
1098 def test_str_newstr():
1099 c_STR = Constant(rstr.STR, lltype.Void)
1100 c_flavor = Constant({'flavor': 'gc'}, lltype.Void)
1101 v1 = varoftype(lltype.Signed)
1102 v2 = varoftype(lltype.Ptr(rstr.STR))
1103 op = SpaceOperation('malloc_varsize', [c_STR, c_flavor, v1], v2)
1104 op1 = Transformer().rewrite_operation(op)
1105 assert op1.opname == 'newstr'
1106 assert op1.args == [v1]
1107 assert op1.result == v2
1108
1109 def test_malloc_varsize_zero():
1110 c_A = Constant(lltype.GcArray(lltype.Signed), lltype.Void)
1111 v1 = varoftype(lltype.Signed)
1112 v2 = varoftype(c_A.value)
1113 c_flags = Constant({"flavor": "gc", "zero": True}, lltype.Void)
1114 op = SpaceOperation('malloc_varsize', [c_A, c_flags, v1], v2)
1115 op1 = Transformer(FakeCPU()).rewrite_operation(op)
1116 assert op1.opname == 'new_array_clear'
1117
1118 def test_str_concat():
1119 # test that the oopspec is present and correctly transformed
1120 PSTR = lltype.Ptr(rstr.STR)
1121 FUNC = lltype.FuncType([PSTR, PSTR], PSTR)
1122 func = lltype.functionptr(FUNC, 'll_strconcat',
1123 _callable=rstr.LLHelpers.ll_strconcat)
1124 v1 = varoftype(PSTR)
1125 v2 = varoftype(PSTR)
1126 v3 = varoftype(PSTR)
1127 op = SpaceOperation('direct_call', [const(func), v1, v2], v3)
1128 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1129 op1 = tr.rewrite_operation(op)
1130 assert op1.opname == 'residual_call_r_r'
1131 assert op1.args[0].value == func
1132 assert op1.args[1] == ListOfKind('ref', [v1, v2])
1133 assert op1.args[2] == 'calldescr-%d' % effectinfo.EffectInfo.OS_STR_CONCAT
1134 assert op1.result == v3
1135
1136 def test_str_promote():
1137 PSTR = lltype.Ptr(rstr.STR)
1138 v1 = varoftype(PSTR)
1139 v2 = varoftype(PSTR)
1140 op = SpaceOperation('hint',
1141 [v1, Constant({'promote_string': True}, lltype.Void)],
1142 v2)
1143 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1144 op0, op1, _ = tr.rewrite_operation(op)
1145 assert op1.opname == 'str_guard_value'
1146 assert op1.args[0] == v1
1147 assert op1.args[2] == 'calldescr'
1148 assert op1.result == v2
1149 assert op0.opname == '-live-'
1150
1151 def test_unicode_promote():
1152 PUNICODE = lltype.Ptr(rstr.UNICODE)
1153 v1 = varoftype(PUNICODE)
1154 v2 = varoftype(PUNICODE)
1155 op = SpaceOperation('hint',
1156 [v1, Constant({'promote_unicode': True}, lltype.Void)],
1157 v2)
1158 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1159 op0, op1, _ = tr.rewrite_operation(op)
1160 assert op1.opname == 'str_guard_value'
1161 assert op1.args[0] == v1
1162 assert op1.args[2] == 'calldescr'
1163 assert op1.result == v2
1164 assert op0.opname == '-live-'
1165
1166 def test_double_promote_str():
1167 PSTR = lltype.Ptr(rstr.STR)
1168 v1 = varoftype(PSTR)
1169 v2 = varoftype(PSTR)
1170 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1171 op1 = SpaceOperation('hint',
1172 [v1, Constant({'promote_string': True}, lltype.Void)],
1173 v2)
1174 op2 = SpaceOperation('hint',
1175 [v1, Constant({'promote_string': True,
1176 'promote': True}, lltype.Void)],
1177 v2)
1178 lst1 = tr.rewrite_operation(op1)
1179 lst2 = tr.rewrite_operation(op2)
1180 assert lst1 == lst2
1181
1182 def test_double_promote_nonstr():
1183 v1 = varoftype(lltype.Signed)
1184 v2 = varoftype(lltype.Signed)
1185 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1186 op1 = SpaceOperation('hint',
1187 [v1, Constant({'promote': True}, lltype.Void)],
1188 v2)
1189 op2 = SpaceOperation('hint',
1190 [v1, Constant({'promote_string': True,
1191 'promote': True}, lltype.Void)],
1192 v2)
1193 lst1 = tr.rewrite_operation(op1)
1194 lst2 = tr.rewrite_operation(op2)
1195 assert lst1 == lst2
1196
1197 def test_unicode_concat():
1198 # test that the oopspec is present and correctly transformed
1199 PSTR = lltype.Ptr(rstr.UNICODE)
1200 FUNC = lltype.FuncType([PSTR, PSTR], PSTR)
1201 func = lltype.functionptr(FUNC, 'll_strconcat',
1202 _callable=rstr.LLHelpers.ll_strconcat)
1203 v1 = varoftype(PSTR)
1204 v2 = varoftype(PSTR)
1205 v3 = varoftype(PSTR)
1206 op = SpaceOperation('direct_call', [const(func), v1, v2], v3)
1207 cc = FakeBuiltinCallControl()
1208 tr = Transformer(FakeCPU(), cc)
1209 op1 = tr.rewrite_operation(op)
1210 assert op1.opname == 'residual_call_r_r'
1211 assert op1.args[0].value == func
1212 assert op1.args[1] == ListOfKind('ref', [v1, v2])
1213 assert op1.args[2] == 'calldescr-%d' % effectinfo.EffectInfo.OS_UNI_CONCAT
1214 assert op1.result == v3
1215 #
1216 # check the callinfo_for_oopspec
1217 got = cc.callinfocollection.seen[0]
1218 assert got[0] == effectinfo.EffectInfo.OS_UNI_CONCAT
1219 assert got[1] == op1.args[2] # the calldescr
1220 assert int2adr(got[2]) == llmemory.cast_ptr_to_adr(func)
1221
1222 def test_str_slice():
1223 # test that the oopspec is present and correctly transformed
1224 PSTR = lltype.Ptr(rstr.STR)
1225 INT = lltype.Signed
1226 FUNC = lltype.FuncType([PSTR, INT, INT], PSTR)
1227 func = lltype.functionptr(FUNC, '_ll_stringslice',
1228 _callable=rstr.LLHelpers._ll_stringslice)
1229 v1 = varoftype(PSTR)
1230 v2 = varoftype(INT)
1231 v3 = varoftype(INT)
1232 v4 = varoftype(PSTR)
1233 op = SpaceOperation('direct_call', [const(func), v1, v2, v3], v4)
1234 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1235 op1 = tr.rewrite_operation(op)
1236 assert op1.opname == 'residual_call_ir_r'
1237 assert op1.args[0].value == func
1238 assert op1.args[1] == ListOfKind('int', [v2, v3])
1239 assert op1.args[2] == ListOfKind('ref', [v1])
1240 assert op1.args[3] == 'calldescr-%d' % effectinfo.EffectInfo.OS_STR_SLICE
1241 assert op1.result == v4
1242
1243 def test_unicode_slice():
1244 # test that the oopspec is present and correctly transformed
1245 PUNICODE = lltype.Ptr(rstr.UNICODE)
1246 INT = lltype.Signed
1247 FUNC = lltype.FuncType([PUNICODE, INT, INT], PUNICODE)
1248 func = lltype.functionptr(FUNC, '_ll_stringslice',
1249 _callable=rstr.LLHelpers._ll_stringslice)
1250 v1 = varoftype(PUNICODE)
1251 v2 = varoftype(INT)
1252 v3 = varoftype(INT)
1253 v4 = varoftype(PUNICODE)
1254 op = SpaceOperation('direct_call', [const(func), v1, v2, v3], v4)
1255 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1256 op1 = tr.rewrite_operation(op)
1257 assert op1.opname == 'residual_call_ir_r'
1258 assert op1.args[0].value == func
1259 assert op1.args[1] == ListOfKind('int', [v2, v3])
1260 assert op1.args[2] == ListOfKind('ref', [v1])
1261 assert op1.args[3] == 'calldescr-%d' % effectinfo.EffectInfo.OS_UNI_SLICE
1262 assert op1.result == v4
1263
1264 def test_str2unicode():
1265 # test that the oopspec is present and correctly transformed
1266 PSTR = lltype.Ptr(rstr.STR)
1267 PUNICODE = lltype.Ptr(rstr.UNICODE)
1268 FUNC = lltype.FuncType([PSTR], PUNICODE)
1269 func = lltype.functionptr(FUNC, 'll_str2unicode',
1270 _callable=rstr.LLHelpers.ll_str2unicode)
1271 v1 = varoftype(PSTR)
1272 v2 = varoftype(PUNICODE)
1273 op = SpaceOperation('direct_call', [const(func), v1], v2)
1274 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1275 op1 = tr.rewrite_operation(op)
1276 assert op1.opname == 'residual_call_r_r'
1277 assert op1.args[0].value == func
1278 assert op1.args[1] == ListOfKind('ref', [v1])
1279 assert op1.args[2] == 'calldescr-%d' % effectinfo.EffectInfo.OS_STR2UNICODE
1280 assert op1.result == v2
1281
1282 def test_unicode_eq_checknull_char():
1283 # test that the oopspec is present and correctly transformed
1284 PUNICODE = lltype.Ptr(rstr.UNICODE)
1285 FUNC = lltype.FuncType([PUNICODE, PUNICODE], lltype.Bool)
1286 func = lltype.functionptr(FUNC, 'll_streq',
1287 _callable=rstr.LLHelpers.ll_streq)
1288 v1 = varoftype(PUNICODE)
1289 v2 = varoftype(PUNICODE)
1290 v3 = varoftype(lltype.Bool)
1291 op = SpaceOperation('direct_call', [const(func), v1, v2], v3)
1292 cc = FakeBuiltinCallControl()
1293 tr = Transformer(FakeCPU(), cc)
1294 op1 = tr.rewrite_operation(op)
1295 assert op1.opname == 'residual_call_r_i'
1296 assert op1.args[0].value == func
1297 assert op1.args[1] == ListOfKind('ref', [v1, v2])
1298 assert op1.args[2] == 'calldescr-%d' % effectinfo.EffectInfo.OS_UNI_EQUAL
1299 assert op1.result == v3
1300 # test that the OS_UNIEQ_* functions are registered
1301 cic = cc.callinfocollection
1302 assert cic.has_oopspec(effectinfo.EffectInfo.OS_UNIEQ_SLICE_NONNULL)
1303 assert cic.has_oopspec(effectinfo.EffectInfo.OS_UNIEQ_CHECKNULL_CHAR)
1304
1305 def test_list_ll_arraycopy():
1306 from rpython.rlib.rgc import ll_arraycopy
1307 LIST = lltype.GcArray(lltype.Signed)
1308 PLIST = lltype.Ptr(LIST)
1309 INT = lltype.Signed
1310 FUNC = lltype.FuncType([PLIST]*2+[INT]*3, lltype.Void)
1311 func = lltype.functionptr(FUNC, 'll_arraycopy', _callable=ll_arraycopy)
1312 v1 = varoftype(PLIST)
1313 v2 = varoftype(PLIST)
1314 v3 = varoftype(INT)
1315 v4 = varoftype(INT)
1316 v5 = varoftype(INT)
1317 v6 = varoftype(lltype.Void)
1318 op = SpaceOperation('direct_call', [const(func), v1, v2, v3, v4, v5], v6)
1319 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1320 op1 = tr.rewrite_operation(op)
1321 assert op1.opname == 'residual_call_ir_v'
1322 assert op1.args[0].value == func
1323 assert op1.args[1] == ListOfKind('int', [v3, v4, v5])
1324 assert op1.args[2] == ListOfKind('ref', [v1, v2])
1325 assert op1.args[3] == 'calldescr-%d' % effectinfo.EffectInfo.OS_ARRAYCOPY
1326
1327 def test_list_ll_arraymove():
1328 from rpython.rlib.rgc import ll_arraymove
1329 LIST = lltype.GcArray(lltype.Signed)
1330 PLIST = lltype.Ptr(LIST)
1331 INT = lltype.Signed
1332 FUNC = lltype.FuncType([PLIST]+[INT]*3, lltype.Void)
1333 func = lltype.functionptr(FUNC, 'll_arraymove', _callable=ll_arraymove)
1334 v1 = varoftype(PLIST)
1335 v3 = varoftype(INT)
1336 v4 = varoftype(INT)
1337 v5 = varoftype(INT)
1338 v6 = varoftype(lltype.Void)
1339 op = SpaceOperation('direct_call', [const(func), v1, v3, v4, v5], v6)
1340 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1341 op1 = tr.rewrite_operation(op)
1342 assert op1.opname == 'residual_call_ir_v'
1343 assert op1.args[0].value == func
1344 assert op1.args[1] == ListOfKind('int', [v3, v4, v5])
1345 assert op1.args[2] == ListOfKind('ref', [v1])
1346 assert op1.args[3] == 'calldescr-%d' % effectinfo.EffectInfo.OS_ARRAYMOVE
1347
1348 def test_math_sqrt():
1349 # test that the oopspec is present and correctly transformed
1350 FLOAT = lltype.Float
1351 FUNC = lltype.FuncType([FLOAT], FLOAT)
1352 func = lltype.functionptr(FUNC, 'll_math',
1353 _callable=ll_math.sqrt_nonneg)
1354 v1 = varoftype(FLOAT)
1355 v2 = varoftype(FLOAT)
1356 op = SpaceOperation('direct_call', [const(func), v1], v2)
1357 tr = Transformer(FakeCPU(), FakeBuiltinCallControl())
1358 op1 = tr.rewrite_operation(op)
1359 assert op1.opname == 'residual_call_irf_f'
1360 assert op1.args[0].value == func
1361 assert op1.args[1] == ListOfKind("int", [])
1362 assert op1.args[2] == ListOfKind("ref", [])
1363 assert op1.args[3] == ListOfKind('float', [v1])
1364 assert op1.args[4] == 'calldescr-%d' % effectinfo.EffectInfo.OS_MATH_SQRT
1365 assert op1.result == v2
1366
1367 def test_quasi_immutable():
1368 from rpython.rtyper.rclass import FieldListAccessor, IR_QUASIIMMUTABLE
1369 accessor = FieldListAccessor()
1370 accessor.initialize(None, {'inst_x': IR_QUASIIMMUTABLE})
1371 v2 = varoftype(lltype.Signed)
1372 STRUCT = lltype.GcStruct('struct', ('inst_x', lltype.Signed),
1373 ('mutate_x', rclass.OBJECTPTR),
1374 hints={'immutable_fields': accessor})
1375 for v_x in [const(lltype.malloc(STRUCT)), varoftype(lltype.Ptr(STRUCT))]:
1376 op = SpaceOperation('getfield', [v_x, Constant('inst_x', lltype.Void)],
1377 v2)
1378 tr = Transformer(FakeCPU())
1379 [_, op1, op2] = tr.rewrite_operation(op)
1380 assert op1.opname == 'record_quasiimmut_field'
1381 assert len(op1.args) == 3
1382 assert op1.args[0] == v_x
1383 assert op1.args[1] == ('fielddescr', STRUCT, 'inst_x')
1384 assert op1.args[2] == ('fielddescr', STRUCT, 'mutate_x')
1385 assert op1.result is None
1386 assert op2.opname == 'getfield_gc_i_pure'
1387 assert len(op2.args) == 2
1388 assert op2.args[0] == v_x
1389 assert op2.args[1] == ('fielddescr', STRUCT, 'inst_x')
1390 assert op2.result is op.result
1391
1392 def test_quasi_immutable_setfield():
1393 from rpython.rtyper.rclass import FieldListAccessor, IR_QUASIIMMUTABLE
1394 accessor = FieldListAccessor()
1395 accessor.initialize(None, {'inst_x': IR_QUASIIMMUTABLE})
1396 v1 = varoftype(lltype.Signed)
1397 STRUCT = lltype.GcStruct('struct', ('inst_x', lltype.Signed),
1398 ('mutate_x', rclass.OBJECTPTR),
1399 hints={'immutable_fields': accessor})
1400 for v_x in [const(lltype.malloc(STRUCT)), varoftype(lltype.Ptr(STRUCT))]:
1401 op = SpaceOperation('jit_force_quasi_immutable',
1402 [v_x, Constant('mutate_x', lltype.Void)],
1403 varoftype(lltype.Void))
1404 tr = Transformer(FakeCPU(), FakeRegularCallControl())
1405 tr.graph = 'currentgraph'
1406 op0, op1 = tr.rewrite_operation(op)
1407 assert op0.opname == '-live-'
1408 assert op1.opname == 'jit_force_quasi_immutable'
1409 assert op1.args[0] == v_x
1410 assert op1.args[1] == ('fielddescr', STRUCT, 'mutate_x')
1411
1412 def test_no_gcstruct_nesting_outside_of_OBJECT():
1413 PARENT = lltype.GcStruct('parent')
1414 STRUCT = lltype.GcStruct('struct', ('parent', PARENT),
1415 ('x', lltype.Signed))
1416 v_x = varoftype(lltype.Ptr(STRUCT))
1417 op = SpaceOperation('getfield', [v_x, Constant('x', lltype.Void)],
1418 varoftype(lltype.Signed))
1419 tr = Transformer(None, None)
1420 py.test.raises(NotImplementedError, tr.rewrite_operation, op)
1421
1422 def test_no_fixedsizearray():
1423 A = lltype.FixedSizeArray(lltype.Signed, 5)
1424 v_x = varoftype(lltype.Ptr(A))
1425 op = SpaceOperation('getarrayitem', [v_x, Constant(0, lltype.Signed)],
1426 varoftype(lltype.Signed))
1427 tr = Transformer(None, None)
1428 tr.graph = 'demo'
1429 py.test.raises(NotImplementedError, tr.rewrite_operation, op)
1430 op = SpaceOperation('setarrayitem', [v_x, Constant(0, lltype.Signed),
1431 Constant(42, lltype.Signed)],
1432 varoftype(lltype.Void))
1433 e = py.test.raises(NotImplementedError, tr.rewrite_operation, op)
1434 assert str(e.value) == (
1435 "'demo' uses %r, which is not supported by the JIT codewriter" % (A,))
1436
1437 def _test_threadlocalref_get(loop_inv):
1438 from rpython.rlib.rthread import ThreadLocalField
1439 tlfield = ThreadLocalField(lltype.Signed, 'foobar_test_',
1440 loop_invariant=loop_inv)
1441 OS_THREADLOCALREF_GET = effectinfo.EffectInfo.OS_THREADLOCALREF_GET
1442 c = const(tlfield.getoffset())
1443 v = varoftype(lltype.Signed)
1444 op = SpaceOperation('threadlocalref_get', [c], v)
1445 cc = FakeBuiltinCallControl()
1446 cc.expected_effect_of_threadlocalref_get = (
1447 effectinfo.EffectInfo.EF_LOOPINVARIANT if loop_inv
1448 else effectinfo.EffectInfo.EF_CANNOT_RAISE)
1449 tr = Transformer(FakeCPU(), cc)
1450 op0 = tr.rewrite_operation(op)
1451 assert op0.opname == 'residual_call_ir_i'
1452 assert op0.args[0].value == 'threadlocalref_get' # pseudo-function as str
1453 assert op0.args[1] == ListOfKind("int", [c])
1454 assert op0.args[2] == ListOfKind("ref", [])
1455 assert op0.args[3] == 'calldescr-%d' % OS_THREADLOCALREF_GET
1456 assert op0.result == v
1457
1458 def test_threadlocalref_get_no_loop_inv():
1459 _test_threadlocalref_get(loop_inv=False)
1460
1461 def test_threadlocalref_get_with_loop_inv():
1462 _test_threadlocalref_get(loop_inv=True)
1463
1464 def test_unknown_operation():
1465 op = SpaceOperation('foobar', [], varoftype(lltype.Void))
1466 tr = Transformer()
1467 try:
1468 tr.rewrite_operation(op)
1469 except Exception as e:
1470 assert 'foobar' in str(e)
1471
1472 def test_likely_unlikely():
1473 v1 = varoftype(lltype.Bool)
1474 v2 = varoftype(lltype.Bool)
1475 op = SpaceOperation('likely', [v1], v2)
1476 tr = Transformer()
1477 assert tr.rewrite_operation(op) is None
1478 op = SpaceOperation('unlikely', [v1], v2)
1479 assert tr.rewrite_operation(op) is None
1480
1481 def test_uint_mul_high():
1482 v3 = varoftype(lltype.Signed)
1483 for v1 in [varoftype(lltype.Signed), const(42)]:
1484 for v2 in [varoftype(lltype.Signed), const(42)]:
1485 op = SpaceOperation('direct_call', [Constant('uint_mul_high'), v1], v3)
1486 op = Transformer(FakeCPU())._handle_int_special(op, 'int.uint_mul_high',
1487 [v1, v2])
1488 assert op.opname == 'uint_mul_high'
1489 assert op.args == [v1, v2]
1490 assert op.result == v3